Rotate Image towards mouse click - shortest distance

R

Richard Mountain

Guest
Objective:
I'm trying to get an image to rotate ( with animation ) towards the angle where I click on screen via the shortest route.

For example:
image_angle = 10
point_direction = 140
This time image will rotate clockwise.
( I have this working up until the point image_angle reaches 360, then it breaks going from 360 to 0.. 1.. 2.. etc..).

I'm struggling with:
image_angle = 10
point_direction = 220
This time the image should rotate anti clockwise.

Here is what I have up to now, is there a simpler solution?

Code:
/// Ship movement logic

direction = obj_player.image_angle; 

if ( global.attack_current_angle )
{
    // Rotate image
   
   
    // Check for shortest route
    if ( ( direction + 180 ) > global.attack_current_angle )
    {
        // Shorter route is +
        direction += 3;
       
        // If the value reaches 360 the need to convert it to 0
        if ( direction >= 360 ) direction = 0;   
       
        // Player angle > clicked point then stop
        if ( direction > global.attack_current_angle )
        {
            direction = global.attack_current_angle;
            global.attack_current_angle = false;
        }
    }
    else
    {
        // Shorter route is -
    }
}
else
{
    // Check to see whether mouse has been clicked
    if ( !ds_queue_empty( global.attack_queue ) )
    {
        // Mouse has been clicked
        global.attack_current_angle = ds_queue_dequeue( global.attack_queue );
    }
}

obj_player.image_angle = direction;

// Debug
global.debug_text[0] = "Image Angle: " + string( obj_player.image_angle );
 
Z

Zekka

Guest
Game Maker provides a builtin called angle_difference() which returns the shortest offset between two angles. (for instance, for 300 and 60, it returns 120 rather than -240, and for 30 and 270, it returns -120, rather than 240.)

You can take the sign() of that to get the rotate direction that brings you closer. Then just check if the abs(current angle - angle-to-mouse) is less than your rotation speed -- if so, set the current angle to the angle-to-mouse. This can be done in about 5 lines of code.
 
R

Richard Mountain

Guest
Fantastic that makes much more sense.

@Zekka thank you for that, I will get that implemented tonight when I get home
 
Top