- Home /
Push object away from another object
Hi all. I have a moving sphere with a rigidbody on it. At some event I destroy this sphere and instantiate 2 smaller spheres.
GameObject pop1 = Instantiate (spherePrefab, new Vector3 (parentPos.x, 0 , parentPos.z), transform.rotation) as GameObject;
pop1.rigidbody.velocity = parentVel;
GameObject pop2 = Instantiate (spherePrefab, new Vector3 (parentPos.x, 0 , parentPos.z), transform.rotation) as GameObject;
pop2.rigidbody.velocity = parentVel;
These 2 spheres are instantiated in the same place, and as they are rigidbodies, they show up one aside another and they have the same velocity as parent sphere.
Could you please tell me how can I make 2 smaller sphere move away from each other as well, as shown on the second picture?
thanks, but I know about this method. The problem is much deeper. I'll write an answer right now.
Answer by artman_12 · Feb 05, 2013 at 03:01 PM
The problem is much deeper, than it seems in the first place. I'm instantiating 2 smaller spheres in the same position as the parent sphere. This is my main mistake. I should instantiate them a bit to the sides. to calculate this offset I turned velocity vector to -90 degrees, normalized it, multiplied by sphere radius and cached this value. It would be used for 1st sphere I've done the same for another sphere, but the radius was 180, instead of -90. thus I've got 2 points in the world, where I can instantiate 2 smaller spheres.
Vector3 vel = parentSphere.rigidbody.velocity;
Vector3 newVel1 = Quaternion.AngleAxis(-90, Vector3.up) * vel;
Vector3 offset1 = newVel1.normalized * parentSphereRadius;
Vector3 newVel2 = Quaternion.AngleAxis(180, Vector3.up) * vel;
Vector3 offset2 = newVel1.normalized * parentSphereRadius;
Now I have to calculate vector to push my spheres apart from each other.
GameObject pop1 = Instantiate (spherePrefab, new Vector3 (parentPos.x, 0 , parentPos.z), transform.rotation) as GameObject;
Vector3 pop1Delta = parentPos - pop1.transform.position;
pop1.rigidbody.velocity = parentVel;
pop1.rigidbody.AddForce(pop1Delta);
GameObject pop2 = Instantiate (spherePrefab, new Vector3 (parentPos.x, 0 , parentPos.z), transform.rotation) as GameObject;
Vector3 pop2Delta = parentPos - pop2.transform.position;
pop2.rigidbody.velocity = parentVel;
pop1.rigidbody.AddForce(pop2Delta);
That's it! Now it works correctly.