Rotation using Unity2D

I have a game object at the top middle of my screen. I have no idea how to be able to rotate it so it will follow my mouse pointer or even touch position. It doesn’t matter which, I’m currently building it follow my mouse position so let’s stick with coding it “LookAt” my mouse pointer.

If you don’t understand what I want to be able to do, let’s take a look at this simple image.
20632-rotation.png

The game object (a 2D sprite) should be able to rotate back and forth to point at an x and y coordinate where my mouse pointer is. Every time I tried to use LookRotation or LookAt, I just got weird results that always rotated it incorrect ways. Can somebody help me along here in getting this up and going?

P.S. Preferably in Javascript.

Thanks a ton!

are you looking for Transform.LookAt maybe?

I don’t know enough to know that or not. But i did change

this line -

transform.rotation = Quaternion.LookRotation(lookDir);

to this -

transform.LookAt(lookDir);

and i still have the same problem with it.

I never used the new 2d features since I stick with unity 4.0 at the moment. However most people forget that LookAt or LookRotation takes two parameters. If you don’t pass a second it defaults to Vector3.up which is just a constant for (0, 1, 0).

The second parameter controls the rotation around the look-at-axis.

LookAt makes the object’s forward axis (z, the blue one) to point directly at the target position (the first parameter). The second parameter just rotates the object around the forward axis so the object’s up axis (y, the green one) points most closely to the given up-vector in the second parameter.

Depending on where “up” is on your object you might want to pass a different up-vector.