- Home /
Weird 2D Mouse Look At Problem
Okay, so yesterday I decided to start making a 2D top-down shooter. So I started with the main mechanic; getting the player to aim at the mouse, but came across this really strange problem where the player would not fully rotate. The player has a Recttransform component, and is a child of a 'Screen space - overlay' canvas. I have tried various options for rotating the player, but opted for the following:
  Vector3 dir = Input.mousePosition - cam.WorldToScreenPoint(transform.position).normalized;
  float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
  transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
 I recorded a video showing the problem: https://www.youtube.com/watch?v=1jmFl9gpEbo 
Any help would be appreciated!
Answer by Lethael · Jan 25, 2018 at 05:37 AM
Yay! I finally got it working. If I set the canvas's render mode to 'Screen space - Camera', it works perfectly, well nearly. (It rotates it by 90 degrees, but I was able to easily fix that.)
Answer by Zwithak · Jan 25, 2018 at 04:55 AM
The main problem is that you are normalizing the screen-point vector. Though, I'd recommend working in game-coordinates (as opposed to screen-coordinates) as you should be able to make a point you can simply rotate to (or set as your forward, in this case).
But, using screen coordinates, something like this, perhaps:
     public static Vector2 FaceMouse(Camera cam, Transform player)
     {
         player.forward = Input.mousePosition - cam.WorldToScreenPoint(player.position);
     }
Or just use that as a base reference and go from there.
@Zwithak Thanks for the fast reply ;) 
 I tried what you suggested, but unfortunately did not make any positive improvements. I have tried heaps of different ways to do this, (including without normalising the screen-space vector) but haven't got it to work. I think there may be something wrong with my setup, as I have used mulitple scripts other's have made, who claim that their script's work. 
 Also, if i do this:
  Vector3 dir = cam.ScreenToWorldPoint(Input.mousePosition) - transform.position;
 The exact same problem occurs.
I know you already found a solution, but I fixed the code above so that should also work now. Just keep in $$anonymous$$d that in 3d environments, you need to correct for the camera height.
Oh yeah, I should have mentioned, the code I posted in the question works fine, except I had to change this:
 transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
to this:
 transform.rotation = Quaternion.AngleAxis (angle - 90, Vector3.forward);
I can't test your code right now, but I think it would also work.
 So anyway, thanks for the help ;) 
 BTW: Did you subscribe to me on Youtube? xD
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                