- Home /
How to attach objects with a hinge on collide
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.
Your answer
Follow this Question
Related Questions
Vector3.MoveTowards doesnt work 1 Answer
Instantiated object not showing in scene or hierarchy 2 Answers
re-entering on the opposite side? 1 Answer
Scene overlapping on real device 1 Answer