2
\$\begingroup\$

Given the sprites X and Y values, and the mouses X and Y values, how can I make the sprite face the mouse cursor?

I tried doing this in my move method which I found in another SO question:

    private function move(mousePosX:Number, mousePosY:Number) {
        if(key.isDown(Keyboard.A))
            this.vx -= this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.D))
            this.vx += this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.W))
            this.vy -= this.speed;
        else
            this.vy *= this.friction;
        if(key.isDown(Keyboard.S))
            this.vy += this.speed;
        else
            this.vy *= this.friction;

        this.x += vx;
        this.y += vy;

        // Make the player face the cursor
        this.rotation = Math.atan2(this.x - mousePosX, this.y - mousePosY);
    }

And rotation does happen, but it's of one or two pixels. this.x and this.y are the sprite X and Y values.

Cheers!

EDIT: Got it. here's the final calculation:

this.rotation = -(Math.atan2(this.x - mousePosX, this.y - mousePosY) * 180 / Math.PI);
\$\endgroup\$
1

1 Answer 1

0
\$\begingroup\$

Trying to speed answer your question,

I guess you are halfway there, you probably are getting the rotation in radians from Math.atan2() call, and you're graphics library deals with degrees!

degree_angle = rotation * 180 / 3.1415926 (PI);

Anyway, as a bonus, if you actually need movement in the mouse direction, the direction vector would be such as v(cos(rotation), sin(rotation)). Then multiply that for the desired movement "speed", and there it goes, following the mouse.

Please correct me if i'm wrong :)

\$\endgroup\$
2
  • \$\begingroup\$ That formula you posted worked, thanks :) Updated my question with the answer. \$\endgroup\$ Feb 22, 2012 at 2:20
  • \$\begingroup\$ great! good programming !:) \$\endgroup\$
    – Grimshaw
    Feb 22, 2012 at 2:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .