According to Collision Change Rotation of Car
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.
Answer by siddharth3322 · Jan 31, 2017 at 04:48 PM
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.
Your answer
Follow this Question
Related Questions
2D collision trouble, character falling through map 1 Answer
Rotate camera on collision of character 1 Answer
I have two RaycastHit2Ds but only one is activating 0 Answers
OnTriggerExit not working 0 Answers
Improve ParticleSystem physic 0 Answers