0
\$\begingroup\$

Basically I want to give rotation to player car as per collision occur with wall. Following image gives you over all idea.

enter image description here

I have following code that giving me correct collision reflection but its in position form not for rotation.

void OnCollisionEnter2D (Collision2D other)
{
    ContactPoint2D contact = other.contacts [0];
//      Vector3 reflectedVelocity = Vector3.Reflect (direction, contact.normal);      
//      direction = reflectedVelocity;

    Quaternion reflectedRot = Quaternion.FromToRotation (transform.up, contact.normal);
    transform.rotation *= reflectedRot;
}

What I have to do for getting correct collision rotation for car? As well smooth turn for car on same rotation so car start moving on that way.

Please give me some help for this.

\$\endgroup\$
0
\$\begingroup\$

Here is a script I wiped up I think it does what you want. Its pretty self explanatory.

   using UnityEngine;

public class Test : MonoBehaviour {
    Vector3 velocity;
    float speed = 5;
    float rotationSpeed = 5;
    void Start()
    {
       // velocity = -transform.up;// This just makes the my cube "fall" in my test scene
         velocity = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), 0f);
    }
    void Update()
    {
        if (velocity != Vector3.zero)
        {
            //transform.rotation = Quaternion.Slerp(
            //    transform.rotation,
            //    Quaternion.LookRotation(velocity),
            //    Time.deltaTime * rotationSpeed
            //);
            float angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.AngleAxis(angle -90, Vector3.forward),Time.deltaTime*rotationSpeed);
        }
        transform.position += velocity * Time.deltaTime * speed;
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        ContactPoint2D contact;
        contact = other.contacts[0];
        velocity = 2 * (Vector3.Dot(velocity, Vector3.Normalize(contact.normal))) * Vector3.Normalize(contact.normal) - velocity; //Following formula  v' = 2 * (v . n) * n - v

        velocity *= -1;// Dont know why I had to multiply by -1 but it's inversed otherwisae
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.