x


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.

more ▼

asked Apr 23 '11 at 11:58 AM

Jason Hamilton gravatar image

Jason Hamilton
445 68 73 80

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
}
more ▼

answered Apr 23 '11 at 12:26 PM

Seregon gravatar image

Seregon
131 6

I guess you want to write PlayerPosition.x inside the two if statements but beside that everything is ok.

Apr 23 '11 at 01:10 PM Bunny83

I hadn't spotted that, thanks. I've fixed the code now.

Apr 23 '11 at 01:35 PM Seregon

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?

Apr 24 '11 at 03:01 AM Jason Hamilton

woops I meant to say subtract camer.main from Playerposition....

Apr 24 '11 at 03:02 AM Jason Hamilton

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.

Apr 24 '11 at 10:30 PM Seregon
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3003
x2167
x983
x886
x485

asked: Apr 23 '11 at 11:58 AM

Seen: 1527 times

Last Updated: Apr 23 '11 at 11:58 AM