rotation, vector bounce problem

Problem visualized: rotation problem - Album on Imgur


Code

void OnCollisionEnter2D (Collision2D collision)
{
    Vector2 normal = collision.GetContact(0).normal;
    Vector3 reflect = Vector3.Reflect(transform.up, normal); 
    transform.rotation = Quaternion.LookRotation(reflect);
}

Everytime the object hits a platform it should bounce off of it. The red line represents the expected result, the blue lines the current result in the pic. Since the game is 2D, i only want to rotate on the z axis, not on x or y.

Well, LookRotation calculates a 3d rotation and alignes the forward axis (z - axis) with the first vector you provide and also rotates this forward axis so that the up vector is aligned with the given up vector in the second parameter. If you are in a 2d environment your usage of LookRotation is completely wrong. You do not pass any up vector so you implicitly use Vector3.up.

As you said in 2d you don’t want any rotation beside around the fix z axis. In many cases people don’t use LookRotation at all in 2d since it wasn’t meant to be used in 2d. It’s common to use Mathf.Atan2 to calculate the angle a certain direction vector describes with the world x axis. However you can use LookRotation as well. Though you have to pass Vector3.forward as first parameter since you want to keep the forward axis aligned with the world forward axis. Instead you want to pass your 2d direction vector as second parameter which describes the up vector.

Note that if your “desired” direction vector should not be aligned with the objects up vector but with its right vector you just have to rotate your vector 90 clockwise. Since we work in 2d that’s trivial since you just have to swap the x and y components and flip the sign of one of them. Which one controls in which direction you rotate (clockwise or counterclockwise).

Assuming you want to align the objects up vector in the direction you specify, you want to do:

Vector2 normal = collision.GetContact(0).normal;
Vector3 reflect = Vector3.Reflect(transform.up, normal); 
transform.rotation = Quaternion.LookRotation(Vector3.forward, reflect);

If this doesn’t work we need to know more about your object alignment.