- Home /
Keeping balls that stick together together
How do you make rigidbody balls, when they collide, to stick together, even if other things hit them?
I suppose you could have one of them parent to the other upon collision. That "might" be part of how to stick your balls together and keep them stuck.
Parenting was what I tried first, but apparently that just assigns the coordinate system of the child, but does not keep it sticking to the parent.
Forces. Applied to both. Direction and strength of their vectors need to be dependent on each other's position and distance. Something like
ball1.addforce (ball2.x-ball1.x, ball2.y-ball1.y, ball2.z-ball1.z)
...and same for ball2. It's not perfect, but a base to think further. Propably you need a variable before each axis to regulate the strength.
@spacepilot: well that would work of course, but they don't really stick together ;) It's more like gravity, they can still roll on the surface of the other one.
Answer by Bunny83 · Dec 29, 2011 at 03:56 AM
Parenting is the best and easiest solution, just make sure that you turn the childs rigidbody into a kinematic rigidbody.
The problem is that if both balls have the same script, both get the collision message, so you need something to decide who's the master ;)
something like that:
// C#
// Script / classname: "BallScript"
public BallScript master = null;
void OnCollisionEnter(Collision collision)
{
BallScript other = collision.gameObject.Getcomponent<BallScript>();
if (other != null)
{
if (other.master == null) // No master yet?
{
master = this; // Make this one master
other.master = this; // Tell the other
other.rigidbody.isKinematic = true;
collision.transform.parent = transform; // make the other a child of this one.
}
else // We already have a master
{
master = other.master; // So we also use the master
rigidbody.isKinematic = true; // and make us a child of the master
transform.parent = master.transform;
}
}
}
Not sure if setting the rigidbody to kinematic is enough. You might need to use Physics.IgnoreCollision to prevent unwanted collisions with the childs. If that's too compilcated you can also remove the child rigidbodies.