I'm currently replicating a particle system in Unity (C#). I am adding physics to each particle (represented by a sphere) to allow it to bounce off a plane located at the origin. The particle bounces a number of times, being affected by gravity. As the bounces become smaller the sphere starts passing through the plane until finally falling through. The force of gravity will be continuously acting on the particle. What is the proper way to stop the sphere on top of the plane?
I have included my implementation thus far, but the code always eventually allows the sphere to fall through the plane.
DETECTION:
public bool SpherePlaneCollisionDetection(Particle part)
{
Vector3 sphereCenter = part.position;
Vector3 planeCenter = Vector3.zero;
Vector3 normal = Vector3.up;
double radius = 0.5;
Vector3 dist1 = (sphereCenter - planeCenter);
float finalDist = Vector3.Dot (dist1, normal);
if (finalDist > radius) {
return false;
} else {
//Debug.Log ("COLLISION HAS OCCURED");
//Debug.Log ("POSITION: " + part.position);
//Debug.Log ("FINAL DIST: " + finalDist);
return true;
}
}
RESPONSE:
public void HandlePlaneCollision()
{
for (int i=0; i<Particles.Count; i++) {
//Particle p1temp = Particle[i];
Particle tempParticle = (Particle)Particles[i];
//Particle part = tempParticle.GetComponent<Particle>();
float dampning = 0.8f;
float bounce = -1f;
if(SpherePlaneCollisionDetection(tempParticle))
{
tempParticle.velocity.y *= (bounce*dampning);
tempParticle.velocity.x *= friction;
tempParticle.velocity.z *= friction;
Debug.Log(tempParticle.velocity.y);
Particles[i] = tempParticle;
}
}
}
Any help is greatly appreciated.