Basically I want to give rotation to player car as per collision occur with wall. Following image gives you over all idea.
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;
}
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.
For this help, thanks to @UriPopov
Here you have correct answer for this point:
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
}
}
I hope this reply become useful to other users.