- Home /
LookAt() not working with mouse as target in 2D
I have a 2D sprite which I want to look at the mouse:
Vector2 mousePos = Input.mousePosition;
sprite.transform.LookAt (mousePos);
(these are in a loop, btw)
That rotated on the wrong axis. That was pretty easy to fix, though:
Vector3 spriteAngles = Vector3.zero;
spriteAngles.z = -newCity.transform.localEulerAngles.x;
sprite.transform.localEulerAngles = newCityAngles;
That worked. If I moved the mouse in a circle, the sprite moved too. The problem was that it would frequently not move with the mouse. It would move slower or faster than the mouse, or go the complete opposition direction of the mouse, and then change direction once the mouse completed a circle. How would I fix this so it looks directly at the mouse always? My game is on the XY plane, so I want a rotation around the Z axis.
Answer by Buckslice · Dec 21, 2017 at 10:19 PM
I made some code that works (put it in the script on the sprite), it assumes your sprite faces to the right normally. If you are using this for like a turret aiming and tracking the mouse pos or something this will be good, but If you are using for a character sprite you may want to flip the sprite to face the other direction at some point so its not upside down probably.
void Update () {
Vector3 mpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mpos.z = 0.0f; // world units z will mess up our calculations
Vector3 dir = (mpos - transform.position).normalized;
float z = Vector3.SignedAngle(Vector3.right, dir, Vector3.forward);
transform.rotation = Quaternion.Euler(0, 0, z);
}
Your answer
Follow this Question
Related Questions
2D LookAt not working as intended 1 Answer
2D Sprite Rotation 0 Answers
Object Look At Mouse 2 Answers
Mouse cursor position shared beetwen different builds. 3 Answers