- Home /
Attach rigidbodies using a fixed joint on mouseclick
Hi,
What is the proper way to attach two or more rigidbodies together when the player clicks on one of the objects ?
Right now, I can only connect 2 objects together. When I try to connect a third one to the others that are connected, it doesn't work. What can I do to correct that please ? Thanks!
Here's what I've done so far :
void Update()
{
if(Physics.Raycast(Camera.main.ScreenPointToRay(new Vector3((Screen.width / 2), (Screen.height / 2), 0)), out hit, maxBuildDist))
{
if(hit.transform.tag == "piece")
{
if(Input.GetMouseButtonDown(1))
touched = true;
}
}
}
void OnCollisionStay(Collision c)
{
if(!attached)
{
if(touched)
{
var joint = gameObject.AddComponent<FixedJoint>();
joint.connectedBody = c.rigidbody;
joint.enableCollision = true;
attached = true;
touched = false;
}
}
}
have u considered placing the joint upon the object of collision?
c.gameObject.AddComponent<FixedJoint>();
then
c.GetComponent<FixedJoint>().connectedBody = rigibody;
and if i were doing this i would add all the connected objects to List; to manage the objects that i have connected.
Yes, I've tried doing that but it still doesn't work. I can connect two rigidbodies together but not those two to a third one. Thanks anyway
you'll probably want to setup something to assign the object you click to a temporary transform, say for instance On$$anonymous$$ouseDown fill this transform then if this transform is not null and we On$$anonymous$$ouseDown again on a different object connect the two then empty this transform if you need more details just ask.
Heres an example of what i mentioned before, its in c# appologies i don't have time to convert it right now, perhaps it can provide some incite.
public Transform connecter;
public Transform connectee;
RaycastHit hit = new RaycastHit ();
Debug.DrawRay (transform.position, transform.forward * 10);
Physics.Raycast(transform.position, transform.forward * 10, out hit);
if(Input.GetButtonDown("Fire1") && connecter == null) {
if(hit.transform != null && hit.transform.tag == "Click") {
connecter = hit.transform;
}
}
else if(Input.GetButtonDown("Fire1") && connecter != null && connectee == null) {
if(hit.transform != null && hit.transform.tag == "Click") {
connectee = hit.transform;
}
}
if(connecter && connectee != null) {
connecter.gameObject.AddComponent<FixedJoint>();
connecter.GetComponent<FixedJoint>().connectedBody = connectee.rigidbody;
connecter = null;
connectee = null;
}
if(Input.GetButtonDown("Fire2") && connecter != null) {
connecter = null;
connectee = null;
}
}
Thank you for your help skylem, I've tried your code but I don't know how to make it work on my current setup.
I've just replaced hit.transform.tag == "piece" to hit.transform == transform and my code seems to work now ? Strange.
Your answer