Search Unity

Feedback Manually Apply Cars Collision Response Force

Discussion in 'Physics' started by siddharth3322, Feb 28, 2019.

  1. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    I want to throw cars with back force after a collision like this way. Few collision examples, I have represented in the following image with its collision back direction.

    collision_responses.png

    Cars are moving using applied velocity and I have applied velocity continuously to move at constant speed. Just on collision, I have stopped applying velocity for some time so I can get some collision response.

    I want to get collision response as per Bumper.io game:


    At present, I have written some code for this purpose but it's not behaving exactly like this way:

    Code (CSharp):
    1. void OnCollisionEnter(Collision other)
    2. {
    3.     if (other.gameObject.CompareTag(GameConstants.TAG_ENEMY) || other.gameObject.CompareTag(GameConstants.TAG_PLAYER))
    4.     {
    5.         elapsedEngineStartWaiting = 0f;
    6.         StartCoroutine(ApplyReboundForce(other));
    7.     }
    8. }
    9.  
    10. IEnumerator ApplyReboundForce(Collision other)
    11. {
    12.     Vector3 centroid = new Vector3(0, 0, 0);
    13.     foreach (ContactPoint contact in other.contacts)
    14.     {
    15.         centroid += contact.point;
    16.     }
    17.     centroid = centroid / other.contacts.Length;
    18.  
    19.     Vector3 projection = transform.position;
    20.     projection.x = centroid.x;
    21.     Vector3 normaliseCollisionPoint = Vector3.Normalize(projection - centroid);
    22.     float collidedBodyMass = other.gameObject.GetComponent<Rigidbody>().mass;
    23.  
    24.     myRigidbody.velocity = Vector3.zero;
    25.     myRigidbody.angularVelocity = Vector3.zero;
    26.  
    27.     int i = 0;
    28.     while (i < 4)
    29.     {
    30.         myRigidbody.AddForce(normaliseCollisionPoint * GameConstants.CAR_COLLISION_IMPULSE * collidedBodyMass, ForceMode.Impulse);
    31.         yield return new WaitForFixedUpdate();
    32.         i++;
    33.     }
    34. }
    At present, collision response force direction does not remain as per, I mentioned in the above image. I want to force/impulse should be applied in above-mentioned directions.

    Give me some suggestion so I can able to implement suggested things.