- Home /
Mouse.position from center of player
Hey, Im working on a side scroller and the player rotates left or right depending on the position of the mouse in relation to the center of the screen. Heres the code;
var MousePosition = Input.mousePosition;
MousePosition.x -= Screen.width / 2;
MousePosition.y -= Screen.height / 2;
if(MousePosition.x < 0)
{
transform.rotation = Quaternion.Euler(0,180,0);
}
else if(MousePosition.x > 0)
{
transform.rotation = Quaternion.Euler(0,0,0);
}
Now what Id like to do is have the players position on screen (the camera has a Lerp smooth follow thing on it) offset were the rotation takes place, kind of like screen.width is local, if that makes sense.
Answer by Seregon · Apr 23, 2011 at 12:26 PM
You can get the players position on the screen using Camera.WorldToScreenPoint(). Once you have this you can easily compare it to your mouse position, hope this helps:
var MousePosition = Input.mousePosition; var PlayerPosition = Camera.main.WorldToScreenPoint(transform.position);
if(MousePosition.x < PlayerPosition.x) { transform.rotation = Quaternion.Euler(0,180,0); } else if(MousePosition.x > PlayerPosition.x) { transform.rotation = Quaternion.Euler(0,0,0); }
I guess you want to write PlayerPosition.x
inside the two if statements but beside that everything is ok.
Yay! it worked! I love you! I want your babies! etc! etc! one little thing I needed to divide PlayerPosition.x by Camera.main.pixelWidth / 2, where do I post that? do I just answer my own question?
woops I meant to say subtract camer.main from Playerposition....
I'm not sure I understand why you want to do that. I thought the only reason you subtracted half the width was so that you could compare the mouse position to the middle of the screen, and comparing the mouse position to the player position makes that unnecessary? Subtracting half the width from both the player position and mouse position would not affect the result. If I have misunderstood, please explain what your trying to achieve.
Your answer
Follow this Question
Related Questions
rotate camera on mouse reaching edges 1 Answer
Rotate 3rd person Character according to mouse position 0 Answers
Need help on the 3ds max style camera control 0 Answers
Create camera transition from one point to top of object 1 Answer
How to set child position and rotation fixed respect parent? 0 Answers