2

I'm trying to to rotate a sprite, let's say it's a gun, to a point, by taking the smallest route possible on a 360° (right or left depending on what side the point is closer to) and I'm having a few problems.

On a circle, it jumps from 359° to 0° so I can't direcly use my target angle - current angle.

Leep in mind that I'm using SFML so it's executing the function everyframe while isRotating is true.

This is the information that is available to me :

//The angle in degrees of my sprite float currentAngle = pSprite.getRotation(); //The angle is needs to be once the rotation is over float targetAngle = float(atan2(deltaY,deltaX) * 180 / (atan(1)*4) + 180); 

I'm using a speed variable to increment or decrement the value of the angle every frame.

distance = Speed*Time.asSeconds(); currentAngle += distance; 

1 Answer 1

1

First, get the difference:

diff = target - current 

diff is either the "short" angle (the one resulting in a shorter rotation), or the "long" angle (rotation in the other direction which is longer). Notice that:

  • you never need to rotate for more than (as an absolute value) 180 degrees to get from one angle to another.

  • the "short" angle and the "long" angle have opposite signs (+/-) and their absolute values add to 360.

Example: 0 - 359 = -359. This is the "long" angle. We know this because its absolute value is > 180. The "short" angle will have the opposite sign and its absolute value will add up to 360 with 359, so it is 1.

An easy way to calculate this is:

while (diff < -180) diff += 360; while (diff > 180) diff -= 360; 

diff is now the angle you are looking for. So if it is negative, multiply your Speed by -1.

The while (as opposed to if) is there in case the angles are not in [0, 360] - for example, you have current = 1440, target = 359.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.