# make object rotate towards its direction after bounce

i have a 2D game where i have a object that bounces around walls. The world is in x and y and the rotation that is in question is the z axis. Right now i can shoot out a object and it will face towards the direction its heading. I have physics material that allows it to bounce but i disabled the rotation of the rigidbody since it would spin around like crazy.

I want to “flip” the object on bounce. Check out the provided pictures. This is how the bounce should function logically, but i need to code the rotation when the bounce happens so that the object rotates towards the new direction it is heading. I figured this would be easy to code, i had an original code for this but it wasnt a solution necessarily more a bandaid fix that only worked if the obstacles had either x = 0 or y = 0. With the logic presented in the pictures, how would you suggest i code the object to rotate in the manner in pic 3?

EDIT: Figured the best way to solve this is using Vector3.Reflect and use the reflect on transform.rotation.z, but how would i go about doing this?

Well i guess ill answer this myself. I managed to solve it and no, Vector3.reflect() is not needed. The key is to track the original direction of the object as a Vector3 while also tracking the new direction in a seperate Vector3 after collision.

``````    Vector3 newDir = new Vector3(transform.position.x, transform.position.y, 0);
float newDirValue = Mathf.Atan2(newDir.y - currDir.y, newDir.x - currDir.x);
float newDirValueDeg = (180 / Mathf.PI) * newDirValue;
transform.rotation = Quaternion.Euler(0, 0, newDirValueDeg);
``````

This will calculate and set the transform.rotation.z of the object in the new direction its taking. currDir is the name of the Vector3 variable that keeps track of the original direction before collision.

``````    void FixedUpdate()
{
currDir = new Vector3(transform.position.x, transform.position.y, 0);
}
``````

This part is important considering physic simulations (the bounce material) is called before OnCollisionEnter(). However, OnCollisionEnter() is called within FixedUpdate(). This allows the values of currDir to be utilized in the collision code before the values of currDir became identical to newDIr.