Programmatically attach two objects with a hinge joint - unity3d

I have a ball that is attached to the bottom of a bar with a hinge joint that is swinging back and forth. The hinge joint is on the ball and attaches to the bar. When I tap the screen the hinge joint on the ball is destroyed and depending on the position of the ball will throw it using the built in physics.
I want to collide with another swinging bar and attach to it with a hinge joint. So basically a swinging game for a ball where you swing from bar to bar.
I can destroy the hinge joint just fine. How do I reattach it to the object it has collided with? I have the following:
Attach ball:
using UnityEngine;
using System.Collections;
public class attachBall : MonoBehaviour {
public GameObject player;
void OnTriggerEnter2D(Collider2D collider) {
if (collider.tag == "Player")
{
print ("COLLISION DETECTED!");
player.AddComponent<HingeJoint2D>();
}
}
}
Release ball:
using UnityEngine;
using System.Collections;
public class releaseBall : MonoBehaviour {
public GameObject player;
void Update(){
if (Input.GetMouseButtonDown (0)) {
Destroy(player.GetComponent("HingeJoint2D"));
}
}
}
I have placed a 2d circle collider on both the ball and the bar it is to collide with. It has a collision but when it does it locks the ball in place. I want it to attach to the bar it has collided with and swing with it.

Figured it out.
I had the script on the rope originally but I moved it to the ball.
Then I find the gameobject with the tag "Player" to re-attach the hinge joint to the ball.
Then I defined the object that I collided with and place it in the GameObject "rope".
Then I had to define the hinge I added and the rigidbody already attached to the rope.
After setting it as the connectedBody I moved the connected anchor to be on the end of the rope.
And voila. Ball swings on the rope.
using UnityEngine;
using System.Collections;
public class attachBall : MonoBehaviour {
public GameObject player;
public GameObject rope;
public HingeJoint2D hinge;
public Rigidbody2D rb;
public bool attached = false;
void OnTriggerEnter2D(Collider2D collider) {
if (collider.tag == "rope" && !attached)
{
Debug.Log ("collision");
attached = true;
player = GameObject.FindGameObjectWithTag ("Player");
player.AddComponent<HingeJoint2D> ();
rope = collider.gameObject;
hinge = player.GetComponent<HingeJoint2D>();
rb = rope.GetComponent<Rigidbody2D>();
hinge.connectedBody = rb;
hinge.connectedAnchor = new Vector2(0,-2.5f);
}
}
}

Related

How to make 3D object climb up wall in Unity 3D

I am trying to make a 3D capsule climb up along an object I tagged as "Wall". However, when I make contact with the wall, It can't seem to rise along the wall. How would this be fixed?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallClimb : MonoBehaviour
{
public float riseSpeed;
public Rigidbody rb;
private void start()
{
riseSpeed = 5.0f;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Wall"))
{
Debug.Log("Position: " + transform.position);
rb.velocity = transform.up * riseSpeed;
Debug.Log("Wall Hit");
}
}
}
Maybe when you are pressing 'w' there are 2 forces acting on the wall 1 is upward and 1 in direction of the wall, and the force in direction of the wall won't let you go upwards, also make sure there is no friction on the wall.

Shooting bullets in unity2D

I'm trying to shoot bullets in a 2D top-down-shooter game but they just stay rest and doesnt move
I tried to add "addforce" but they didnt move. I changed it with "new Vector2" but that time it doesnt follow my cursor. istead of it shoots in a different same direction.I want to shoot to my cursor. and if possible I want to add a fire delay between object and make it possible to attack repeatly while holding mouse left button.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 15f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
Shoot();
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab,firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.right* bulletForce, ForceMode2D.Impulse);
}
}//class
`

How to delete the bullet and still shoot?

I'm following a code monkey tutoreal on making a third person game. I tried to copy his code but when he deletes the bullet on impact he can shoot again but when I do it, it does not work.
Bullet code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletProjectile : MonoBehaviour
{
private Rigidbody bulletRigidbody;
[SerializeField] private GameObject playerArmature;
[SerializeField] private Transform vfxHitEnemy;
[SerializeField] private Transform vfxMissEnemy;
private void Awake()
{
bulletRigidbody = GetComponent<Rigidbody>();
}
private void Start()
{
float speed = 20f;
bulletRigidbody.velocity = transform.forward * speed;
}
public void OnTriggerEnter(Collider other)
{
if (other.GetComponent<targetScript>() != null)
{
//hit target
Instantiate(vfxHitEnemy, transform.position, Quaternion.identity);
}
else
{
Instantiate(vfxMissEnemy, transform.position, Quaternion.identity);
}
Destroy(gameObject);
}
}
shooting code:
if (starterAssetsInputs.shoot)
{
Vector3 aimDir = (mouseWorldPosition - bulletSpawn.position).normalized;
Instantiate(pfBullletProjectile, bulletSpawn.position, Quaternion.LookRotation(aimDir, Vector3.up));
starterAssetsInputs.shoot = false;
}
When the bullet is deleted, it won't exist anymore in your game so there won't be anything to shoot anymore.
To fix this you should make your bullet as a prefab, to do this you can just drag your bullet object to the assets folder and maybe make a special folder for those kind of objects.
Then instead of instantiating the bullet that is already in your scene you need to spawn the prefab, then when the bullet is deleted the prefab will still exist and you will be able to spawn it again.

OnCollisionEnter Change Text when triggered

I'm very new to Unity, but not to C#. I'm looking to make a simple solution where when i move a ball into a hole - an event is triggered. The event in this case is changing the text of a TMPro object. I'm seeing nothing being returned when these 2 objects interact using the below code.... Looking for any help on this. More context can be given if needed.
Hole.cs
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Hole : MonoBehaviour
{
// Update is called once per frame
[SerializeField]
private Collision collision;
private TextMeshProUGUI text;
private void Start()
{
text = GetComponent<TextMeshProUGUI>();
}
void Update()
{
//text.text = "Hole hit!";
}
public void OnCollisionEnter(Collision collision)
{
text.text = "Hole hit!";
}
}
BallMover.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallMover : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, vertical);
transform.position += movement * Time.deltaTime;
}
}
Thanks in advance
The Error below "Object Reference not set to instance of an object" is coming up when these 2 object collide...
You need to check are there colliders in both objects.
Collision is a physical event for this reason you have to move the ball with physics, if you move it with transform, it is very likely that you will miss the physics events.
You have to add a "Rigidbody" component to the ball to move physically.
So as you said in a comment you already checked that
You are using Rigidbody
Both objects have Collider components
So additionally make sure
both Collider components are set to IsTrigger = false
Whenever there is physics and Rigidbody involved you do not want to set stuff via transform in Update as this breaks the physics and collision detection! Rather use Rigidbody.MovePosition within FixedUpdate
so something like e.g.
public class BallMover : MonoBehaviour
{
[SerializeField] private Rigidbody _rigidbody;
private void Awake ()
{
if(!_rigidbody) _rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var movement = new Vector3(horizontal, vertical);
_rigidbody.MovePosition(_rigidbody.position + movement * Time.deltaTime);
}
}

NavMeshAgent is still moving after stopped in Unity3D

I was making a simple 3D project with Unity3D. But when using NavMeshAgent, I got a problem that NavMeshAgent was still moving even though it had been stopped. Why this situation is happening, and how can I get rid of this?
Below is GIF:
And this is a picture of NavMeshAgent of that red cube, if it needs:
This is a source code attached to that:
using UnityEngine;
using UnityEngine.AI;
public class PathFinder : MonoBehaviour {
public GameObject target;
private NavMeshAgent nav;
void Start() {
nav = GetComponent<NavMeshAgent>();
if (target != null) nav.SetDestination(target.transform.position);
nav.isStopped = true;
}
}