- Home /
Is it possible for two game objects to reference the same rigid body?
I'm making a simple 2d space game. If the space ship flies off the screen to the left it should appear on the right. So think of the screen as a flattened out sphere.
The way I achieve this is by making a clone of the ship on the opposite side when it starts to leave the screen. When the clone is fully "inside" the screen again I teleport the ship to the clone position and Destroy() the clone (as suggested by this guy).
It works well, but sometimes when a clone exists and it (or the ship) is hit by a rock floating by, the ship and the clone fall out of sync. What I would like is if the clone is hit by a rock, making it drift in a different direction and have it's rotation altered, the same forces should be applied to the ship (and vice versa).
I tried setting the rigidbody2D of the clone to the same as the ships but the property is not setable (GameObject.rigidbody2D). I also thought about writing something in the OnCollisionEnter() to set the velocity and angularvelocity of the ship manually. But I don't know if the physics have been applied at that point and I can't find a clear answer.
Has anyone done anything like this before?
You can use GetComponent to access any component or script on another object.
I can understand your problem but even referencing the same Rigidbody was possible, it still could not solve your problem. You may have to synchronize the 2 via the Update() message by updating the transform info of this one based on the other. However this works only in some limited cases. Generally your problem is something very complicated I think (unless you don't use Rigidbody at all but then you have to manually update the objects collision yourself).
I don't see why having the clones reference the same rigidbody as the original ship wouldn't solve it. I did think about using Update() or perhaps better yet, FixedUpdate(). But I don't think the physics have been calculated yet at the time the function is called. But perhaps it's no a big deal if the rigidbody of the other is updated one physics step later. I'll try it.
Answer by _MGB_ · Mar 03, 2015 at 10:53 AM
You could create your clone, deactivate its rigid body and slave its position to the original ship. Then if/when your original is removed, activate the rigid body on the clone.
Actually, as far as the player is concerned there is only one ship. If the clone is hit by a rock it must also react to it and copy the reaction to the original ship. So my question is basically this: how do I copy physics based reactions between game objects with rigid bodies?