/// <summary> /// Detects collision and sets up for collision with only the ball colliding /// </summary> /// <param name="collision">Collider of other sphere</param> private void OnTriggerEnter(Collider collision) { if (!collisionOccurred) { CodedSpherePhysics otherSphere = collision.gameObject.GetComponent <CodedSpherePhysics>(); if (otherSphere) { collidesWith(otherSphere); } } }
/// <summary> /// Maths for collision between two spheres /// </summary> /// <param name="otherSphere">The sphere being collided with</param> private void collidesWith(CodedSpherePhysics otherSphere) { Vector3 n = (transform.position - otherSphere.transform.position).normalized; Vector3 thisPerp = perpendicularComponent(velocity, n); Vector3 otherPerp = perpendicularComponent(otherSphere.velocity, n); Vector3 u1 = parallelComponent(velocity, n) * sphereCOR; Vector3 u2 = parallelComponent(otherSphere.velocity, n) * sphereCOR; float M1 = mass, M2 = otherSphere.mass; Vector3 v1 = ((M1 - M2) / (M1 + M2)) * u1 + (2 * M2 / (M1 + M2)) * u2; Vector3 v2 = ((M2 - M1) / (M1 + M2)) * u2 + (2 * M1 / (M1 + M2)) * u1; velocity = thisPerp + v1; otherSphere.newVelocityAfterCollisionwith(this, otherPerp + v2); }
/// <summary> /// Sets the new velocity of the other sphere being collided with /// </summary> /// <param name="codedSphere">The sphere being collided with</param> /// <param name="newVelocity">New velocity op the other sphere</param> private void newVelocityAfterCollisionwith(CodedSpherePhysics codedSphere, Vector3 newVelocity) { velocity = newVelocity; collisionOccurred = true; occurredWith = codedSphere; }
// Use this for initialization void Start() { player = GameObject.FindGameObjectWithTag("Player"); playerEngine = player.GetComponent <CodedSpherePhysics>(); main = player.GetComponentInChildren <Camera>(); }