Facing a character towards the mouse

Posted by ratata on Game Development See other posts from Game Development or by ratata
Published on 2013-08-02T12:35:45Z Indexed on 2013/08/02 16:07 UTC
Read the original article Hit count: 208

Filed under:

I'm trying to port a simple 2d top down shooter game from C++(Allegro) to Java and i'm having problems with rotating my character.

Here's the code i used in c++

if (keys[A])
   RotateRight(player, degree);
if (keys[D])
    RotateLeft(player, degree);

void RotateLeft(Player& player, float& degree)
{
    degree += player.rotatingSpeed;
    if ( degree >= 360 )
        degree = 0;
}
void RotateRight(Player& player, float& degree)
{
    degree -= player.rotatingSpeed;
    if ( degree <= 0)
        degree = 360;
}

And this is what i have in render section:

al_draw_rotated_bitmap(player.image, player.frameWidth / 2, player.frameHeight / 2, player.x, player.y, degree * 3.14159 / 180, 0);

Instead of using A-D keys i want to use mouse this time. I've been searching since last night and came up to few sample codes however noone of them worked.

For example this just made my character to circle around the map:

int centerX = width / 2;
int centerY = height / 2;
double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2;

((Graphics2D)g).rotate(angle, centerX, centerY);

g.fillRect(...); // draw your rectangle

Any help is much appreciated.

© Game Development or respective owner

Related posts about mouse