What you are trying to try is not trivial and the use of the internal physics system will be much less problematic.
That said, if you really want to do it by hand, you must first detect the intersections between the balls involved, then solve those problems and then you have to update the speeds.
- Detect intersections between balls
This is simply an intersection test sphere / sphere. Go through all the pairs and check the distance. Distance = (sphere1.transform.position – sphere2.transform.position) .Length ()
If Length <sphere1.radius + sphere2.radius, you have an intersection and you need to solve them
- Intersection resolution
You first calculate the normal of the collision. It's just
NormalOfCollision = sphere1.transform.position - sphere2.transform.position; NormalOfCollision.Normalize ();
You have calculated the distance of the sphere in (1) so that the resolutionDistance is totalRadius – sphereDistance. You then apply this to the bodies.
sphere1.transform.position + = NormalOfCollision * resolutionDistance sphere2.transform.position - = NormalOfCollision * resolutionDistance
If you are going to have different mass spheres colliding, you have to resize the impulse so that the smaller mass is displaced more than the larger one. That is to say.
sphere1Impulse = sphere2Mass / (Sphere1Mass + Sphere2Mass); sphere2Impulse = sphere1Mass / (sphere1Mass + Sphere2Mass); sphere1.transform.position + = NormalOfCollision * resolutionDistance * sphere1Impulse sphere2.transform.position - = NormalOfCollision * resolutionDistance * sphere2Impulse
- Calculation of the speed after impact
You must use linear momentum conservation law. The wikipedia page gives a concrete example.
- The above is a pseudo-code, I did not execute it. It is therefore possible that some of the + / ve signs are displayed in the wrong direction – but that is the right direction.
- This only handles non-angular linear effects (so will not simulate spin shots, etc.)
- If you have larger time steps, or more balls interpenetrating, you must solve the problem until you no longer have contacts (ObjectA can push ObjectB into ObjectC, you have to therefore solve this problem).
- There is no optimization at this level (island collision / large phase, etc.)
- There is no restitution in this with different objects being more elastic than others
- Using PhysX will be much easier than doing everything yourself