- Home /
(solved) 2d sprite rotation towards mouse
Hello,
I am trying to get a 2D sprite, the main character in my game, to point his head towards my mouse upon right click. After looking through a bunch of questions on this topic, I finally got my sprite to rotate along its Z axis to point at my mouse. However, there is still a horrible problem!
At first, I tried fancy stuff like transform.Lookat or Quaternion.LookRotation. But these were messing with my 2D sprites, changing the X and Y rotation. I finally settled on something that I got from here:
http://answers.unity3d.com/questions/10615/rotate-objectweapon-towards-mouse-cursor-2d.html
This is the code I am using:
if (Input.GetButton("Fire2"))
{
cameraDif = Camera.main.transform.position.y - transform.position.y;
mouseX = Input.mousePosition.x;
mouseY = Input.mousePosition.y;
mWorldPos = Camera.main.ScreenToWorldPoint( new Vector3(mouseX, mouseY, cameraDif));
mainPos = Camera.main.ScreenToWorldPoint(transform.position);
diffX = mWorldPos.x - mainPos.x;
diffY = mWorldPos.y - mainPos.y;
float angle = Mathf.Atan2(diffY, diffX) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 90));
This works exactly as I want it to. Except for one problem. Wherever I click on screen, my character's head points to the right. Only if I click far off-screen to the left, he begins to point his head to the left. The point that he changes his orientation, is precisely the left edge of the screen bounds. He also doesn't like to point down although he's apparently cool with pointing up.
It seems like problem here is that either my mouse coordinates are iffy somehow or something went wrong with camera.ScreentoWorld. But I cannot see what could be wrong.
What can I do to fix this?
EDIT:
The problem has been fixed. I was mindlessly converting transform.position with ScreentoWorld when it is already a world position. Silly me.
Answer by kolban · Jun 05, 2012 at 04:41 AM
I am not understanding your code ... but there is something that seems off here:
mainPos = Camera.main.ScreenToWorldPoint(transform.position);
The ScreenToWorldPoint() function takes as input a screen position and returns a world position ... but transform.position is already a world position (and not a screen position). I have no idea what calling ScreenToWorldPoint() with input of a world position would do.