0

I'm trying to rotate an image according to the mouse. The idea is a spaceship game. The tip of the spaceship follows the mouse cursor, depending on the cursor position the spacecraft rotates an angle.

The Allegro rotation function I am using:

al_draw_rotated_bitmap(OBJECT_TO_ROTATE,CENTER_X,CENTER_Y,X,Y,DEGREES_TO_ROTATE_IN_RADIANS);

This is the x and y position of the spaceship:

spaceship.x
spaceship.y

And the x and y position of the mouse cursor:

game_event.mouse.x
game_event.mouse.y

When the right angle to the rotation according to the mouse is identified just send the angle for the "DrawSpaceship" function. This function draws the spaceship in the main loop.

Obs: I'm using C and Allegro5

user50811
  • 11
  • 1

2 Answers2

0
atan ((spaceship.y - game_event.mouse.y) / (spaceship.x - game_event.mouse.x));

With of course a test to avoid to / 0

You will need

#include <math.h>
Ôrel
  • 7,044
  • 3
  • 27
  • 46
  • `atan2(dy, dx)` will take care for the division by zero and also place the angle in the right quadrant according to the sign of `dx` and `dy`. (And then you'd probably have to swap the arguments of your subtractions, so that an angle of 0 means that tha spaceship is headed in (1, 0) direction.) – M Oehm May 27 '15 at 05:39
0
double mouseangle = direction(xscreen - 45, yscreen, xmouse, ymouse); 
animpos = (mouseangle/180.0)*(nframes-1); 

This is more "from scratch" code with a better control and certainly a better practice and could be library independent. You can always adjust the literals.


  • nframes is the number of frames in the image
  • direction is a function that returns the direction between x1 x2 y1 y2 in angles
  • animpos is the animation frame you wish to show
  • xscreen x position of image, screen-related (yscreen is analogous)
  • xmouse mouse's horizontal position, screen-related (xmouse is analogous)
Imobilis
  • 1,475
  • 8
  • 29