# Homing missile problem

This topic is 1327 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm trying to follow this Actionscript tutorial for homing missiles, translating it to C++ with SFML.

But I seem to have a problem with this piece of code:

In Actionscript:

var rotation:int = Math.atan2(targetY, targetX) * 180 / Math.PI;
if (Math.abs(rotation - missile.rotation) > 180)
{
if (rotation > 0 && missile.rotation < 0)
missile.rotation -= (360 - rotation + missile.rotation) / ease;
else if (missile.rotation > 0 && rotation < 0)
missile.rotation += (360 - rotation + missile.rotation) / ease;
}
else if (rotation < missile.rotation)
missile.rotation -= Math.abs(missile.rotation - rotation) / ease;
else
missile.rotation += Math.abs(rotation - missile.rotation) / ease;


Translated in C++ with SFML:

int current = rocket_sprite.getRotation();
if( abs( rotation - current ) > 180 )
{
if( rotation > 0 && current < 0 ) rotation -= ( 360 - rotation + current ) / ease;
else if( current > 0 && rotation < 0 ) rotation += ( 360 - rotation + current ) / ease;
}
else if( rotation < current ) rotation -= abs( current - rotation ) / ease;
else rotation += abs( rotation - current ) / ease;


With this code, the missile acts crazy, getting stuck in places, continually rotating in place for no reason and other stuff like that.

I suspect that the problem lies in the fact that .getRotation() returns absolute values, but I don't know how to even test it.

Here is my complete code:

#include <math.h>
#define PI 3.14159265

class rocket
{
private:
sf::Texture rocket_texture;
sf::Sprite rocket_sprite;
sf::Vector2f position;
int rotation;

public:
rocket();
void rocket_show( sf::RenderWindow * window );
void set_position( sf::Vector2f new_position );
void rocket_rotate( sf::RenderWindow * window );
void rocket_move();
};

rocket::rocket()
{
rotation = 0.f;
}

{
rocket_sprite.setTexture( rocket_texture );

return true;
}

void rocket::rocket_show( sf::RenderWindow * window )
{
rocket_sprite.setOrigin( rocket_texture.getSize().x / 2 , rocket_texture.getSize().y / 2 );
rocket_sprite.setPosition( position );
window->draw( rocket_sprite );
}

void rocket::set_position( sf::Vector2f new_position )
{
position = new_position;
}

void rocket::rocket_rotate( sf::RenderWindow * window )
{
sf::Vector2i mouse_position = sf::Mouse::getPosition( *window );
int targetx = mouse_position.x - position.x;
int targety = mouse_position.y - position.y;

rotation = atan2( targety , targetx ) * 180 / PI;

int ease = 5;
int current = rocket_sprite.getRotation();
if( abs( rotation - current ) > 180 )
{
if( rotation > 0 && current < 0 ) rotation -= ( 360 - rotation + current ) / ease;
else if( current > 0 && rotation < 0 ) rotation += ( 360 - rotation + current ) / ease;
}
else if( rotation < current ) rotation -= abs( current - rotation ) / ease;
else rotation += abs( rotation - current ) / ease;

rocket_sprite.setRotation( rotation );
}

void rocket::rocket_move()
{
int speed = 5;
float speedx = 0;
float speedy = 0;
speedx = speed * ( 90 - abs( rotation ) ) / 90;
if( rotation < 0 ) speedy = -speed + abs( speedx );
else speedy = speed - abs( speedx );
position.x += speedx;
position.y += speedy;
}


If anyone can point me to the right direction, I would really appreciate it. :-)

Thank you in advance. :-)

Edited by Kain5056

##### Share on other sites

Oh! I went through the exact same issue, let me grab how I fixed it! (will edit)

##### Share on other sites

In Dartlang, using the StageXL Lib (you can probably work out the details)

rotationDistance += (rotationDistance > math.PI) ? - 2 * math.PI : (rotationDistance < -math.PI) ? 2 * math.PI : 0;

This is the core logic of the function that set the actual angle of rotation (I had another handle the actual target rotation towards which I was headed).

I realize it's a bit of a complex line, but it was the only way I found out how to fix the angle issue (using radians).
Ended up much simpler than actual degrees.

I know that it ended up working, but there may be better ways to do this, one of the gurus here will probably give an even better solution.

(Edit: That's some dusty old code... my personal next step was leading the target, e.g. making an assumption as to the future target's position and target that as opposed to its current position)
Edited by Orymus3

##### Share on other sites

@Orymus3: Thanks, but I'm not sure how to implement your code, or how it will solve my problem. I will look into it more later, though. :-) Thanks.

@haegarr: Thanks for the info, I also think that the problem lies there, but I'm not sure how to fix it.

I tried

int current = rocket_sprite.getRotation() - 180;


but it does not quite work, even though it does make things a bit better. :-)

I'm still open for ideas...

##### Share on other sites
I tried
int current = rocket_sprite.getRotation() - 180;
but it does not quite work,

It doesn't work because although it matches the pure range of numbers, it does not consider the correct value space. For example, +90° in AS means +90° in SFML, but -90° in AS means +270° in SFML. I have assumed that in both cases 0° points into the same direction and in both cases positive angles are going counter-clockwise; if this isn't true, then things need more thinking...

I also think that the problem lies there, but I'm not sure how to fix it.

There are 2 ways:

1.) You can transform "current" and "rotation" into the same value space as is used by AS (i.e. the if-then-else stuff), and later on transform it back to the value space of SFML. I assume that this solution looks like

int current = rocket_sprite.getRotation();
current = current <= 180 ? current : current - 360;
rotation = rotation <= 180 ? rotation : rotation - 360;


followed by the if-then-else stuff, followed by the reverse transform

rotation = rotation >= 0 ? rotation : rotation + 360;

(I have not tested it.)

2.) Adapt the if-the-else stuff to the value range of SFML (which would be the better alternative, but requires although more thinking).

EDIT: There was an error in the reverse transform.

Edited by haegarr

##### Share on other sites

What units are the angles in rocket_sprite's rotation? Is it in degrees or radians? If it's radians, you're never converting it back to radians before handing it off to rocket_sprite.

If that doesn't fix your problem, I'd test the code to be sure you're getting the correct values you're expecting. There's lots of fiddily bits in there that could go wrong. Pull the code out to a function that takes two positions, and returns the angle. At first just get the math correct without the "ease" logic. Set a breakpoint and step through the debugger with your test cases checking the value at each step.

Most engines/math libraries do everything in radians, so I'd leave everything in radians. If you'd like to display degrees to the user, just convert it before displaying.

- Eck

##### Share on other sites

Here, I found a bit of time:

#include <iostream>
#include <complex>

typedef std::complex<float> C;

// This functions expects all arguments to have length 1
C rotation_towards_with_limit(C current, C target, C max_rotation) {
C desired_rotation = target / current;

if (std::real(desired_rotation) < std::real(max_rotation))
desired_rotation = std::imag(desired_rotation) >= 0.0f ? max_rotation : std::conj(max_rotation);

return desired_rotation;
}

float const Degrees_per_radian = std::atan(1.0f) / 45.0f;
float const Radians_per_degree = 1.0f / Degrees_per_radian;

float convert_to_angle_in_degrees(C z) {
return std::arg(z) * Radians_per_degree;
}

C convert_from_angle_in_degrees(float angle) {
return std::polar(1.0f, angle * Degrees_per_radian);
}

int main() {
C current(1.0f, 0.0f);
C target(-1.0f, 0.0f);
C max_rotation = convert_from_angle_in_degrees(10.0f);

for (int i=0; i<25; ++i) {
std::cout << convert_to_angle_in_degrees(current) << '\n';
current *= rotation_towards_with_limit(current, target, max_rotation);

// You want to normalize periodically to make sure the length doesn't deviate from 1
current /= std::abs(current);
}
}

It is kind of sad that you have to convert the nice unit-length complex number to an angle in degrees to pass it to SFML, because I am sure the first thing SFML does with the angle is convert it to radians and then compute its cosine and sine, which will yield exactly what we started with, after some unnecessary trigonometric operations.

##### Share on other sites

*mindblown by Alvaro's code*

Where can I read more about these:

unit-length complex numbers, which correspond to (cos(angle) + i * sin(angle)).

##### Share on other sites

Where can I read more about these:

unit-length complex numbers, which correspond to (cos(angle) + i * sin(angle)).

I don't know. I learned about complex numbers in high school and college, so I don't have a website to link to. Perhaps you can search the web for multiplication of complex numbers rotation'. Or perhaps you can try Khan Academy...

##### Share on other sites

My highschool taught me matrices but not that.

Thanks, I'll look it up (sorry 'bout the aside here)

##### Share on other sites

This is probably a good starting point for complex notation:

http://betterexplained.com/articles/a-visual-intuitive-guide-to-imaginary-numbers/

That being said, stick with matrices.  Complex notation is meant for 1D problem spaces (where the imaginary part becomes the second dimension).  You're working in a 2D space already, thus no imaginary dimension is needed, so represent your rotations/headings as a 2D unit vector (which is equivalent to a unit length complex number), and utilize matrix algebra to apply the necessary rotations and translations to your game objects.

##### Share on other sites

@Álvaro: Thank you so much for the code example. It's complexity is a bit out of my league for the the time being, though. ^^'  I will study it, but it's a bit more complex than I would like.

haegarr's code is more like what I'm looking for, but, as mentioned, it does not really work. Still, thank you both so much. :-)

To tell you the truth, I don't really know what parts of the code are in radiants and what are in degrees. I assumed it was all in degrees up until now.

I also know pretty much nothing about ActionScript, so the ranges are also a bit of an issue here.

Without the easing, the code works perfectly! The whole problem seems to be just with getRotation() when compared to rotation.

EDIT:

Playing with haegarr's code I tried this and it *almost* works, but still not quite there.

void rocket::rocket_rotate( sf::RenderWindow * window )
{
sf::Vector2i mouse_position = sf::Mouse::getPosition( *window );
float targetx = mouse_position.x - position.x;
float targety = mouse_position.y - position.y;
rotation = atan2( targety , targetx ) * 180 / PI;

int ease = 5;
float current = rocket_sprite.getRotation();

current = current <= 180 ? current : current - 360;
rotation = rotation <= 180 ? rotation : rotation - 360;

if( abs( rotation - current ) > 180 )
{
if( rotation > 0 && current < 0 ) rotation -= ( 360 - rotation + current ) / ease;
else if( current > 0 && rotation < 0 ) rotation += ( 360 - rotation + current ) / ease;
}
else if( rotation < current ) rotation -= abs( current - rotation ) / ease;
else rotation += abs( rotation - current ) / ease;

rotation += 360 / PI;

rocket_sprite.setRotation( rotation );
}

Edited by Kain5056

##### Share on other sites

@Álvaro: Thank you so much for the code example. It's complexity is a bit out of my league for the the time being, though. ^^'  I will study it, but it's a bit more complex than I would like.

I don't think my code is complex: It doesn't have any special cases, and I got it right the first time I wrote it. However, if you are not used to thinking about 2D geometry in terms of complex numbers, it can be pretty hard to understand.

Notice that your code has all the common problems of using angles:
* radians -vs- degrees,
* multiple representations for the same thing (e.g., -90 == 270),
* if you try to pick a single representation, do you use [-180,180) or [0,360)?,
* having to use expensive trigonometric functions,
* difficulty in getting the code right because there are lots of cases to consider.

I could try to fix your angle-based code, but knowing there are much better alternatives, I feel lazy about it.

I really think you should put the effort to learn to think about 2D geometry in terms of either complex numbers or vectors and matrices. Notice that 3D rotations can be represented by unit-length quaternions, which is sort of analogous to representing 2D rotations by unit-length complex numbers. Vectors and matrices also work well in 3D (although interpolating rotations is much harder than with quaternions, and normalizing a rotation matrix is also harder than normalizing a quaternion). However, if you think about 2D geometry in terms of angles, you'll end up pretty confused in 3D, because the natural analog is Euler angles, which are very hard to work with.

##### Share on other sites
Alright, I am a softie and I did write some angle-based code for you. This is pretty much a line-by-line translation of my previous code (which perhaps will let you understand the other code better):

#include <iostream>
#include <cmath>

struct Vector2 {
float x, y;

Vector2(float x, float y) : x(x), y(y) {
}
};

float const Pi = std::atan(1.0f) * 4.0f;

float sane_fmod(float x, float y) {
float scaled_x = x / y;
return (scaled_x - std::floor(scaled_x)) * y;
}

float rotation_towards_with_limit(float current, Vector2 target, float max_rotation) {
float desired_rotation = std::atan2(target.y, target.x) - current;

desired_rotation = sane_fmod(desired_rotation + Pi, 2.0f*Pi) - Pi;

if (std::abs(desired_rotation) > max_rotation)
desired_rotation = desired_rotation >= 0.0f ? max_rotation : -max_rotation;

return desired_rotation;
}

float const Degrees_per_radian = 180.0f / Pi;
float const Radians_per_degree = Pi / 180.0f;

int main() {
float current = 0.0f;
Vector2 target(-1.0f, 0.0f);
float max_rotation = 10.f * Radians_per_degree;

for (int i=0; i<25; ++i) {
std::cout << (current * Degrees_per_radian) << '\n';
current += rotation_towards_with_limit(current, target, max_rotation);
}
}

For your own sanity, make sure you consistently use radians in your computations. You can convert to and from degrees when you need to interface with a human or with an API that uses degrees (which is a bad thing).

##### Share on other sites
I may have done something very wrong in here, I usually commit giant logic mistakes late night.
But could you check my code?
#define RAD_TO_DEG 57.2957795
void rocket::rocket_rotate( sf::RenderWindow * window )
{
sf::Vector2i mouse_position = sf::Mouse::getPosition( *window );
float targetx = mouse_position.x - position.x;
float targety = mouse_position.y - position.y;
rotation = atan2( targety , targetx ); //from -PI to PI
if (rotation < 0) rotation += 2*PI; //from 0 to 2*PI
rotation *= RAD_TO_DEG; //Convert to DEG, ranges from 0 to 360

float current = rocket_sprite.getRotation(); //from 0 to 360

float ease = 0.2;
float difference = current - rotation;

if ( (difference + 360) % 360 < 180 )
// If true, turn right (negative direction)
rocket_sprite.setRotation( rotation - abs(difference) * ease );
else
//If false, turn left (positive direction)
rocket_sprite.setRotation( rotation + abs(difference) * ease );
}

an API that uses degrees (which is a bad thing)

Yes, SFML has this problem. Hundreds of conversions needs to be made every frame which will in turn be converted back (to radians) in order to pass on to OpenGL.
Doesn't make much sense to me, but I guess I got used to it as SDL also uses degrees for angles. It forces us to convert back and forth lots of times whenever we need to do some math. If it was all radians, it would be much easier not having to convert at all (and less error prone). Edited by dejaime

##### Share on other sites

rotation = atan2( targety , targetx ) + PI; //from 0 to 2*PI

When using atan, shouldn't you add 2*PI if angle is < 0, and keep as-is if not:

rotation = atan2(targety, targetx);
if (rotation) < 0
{
rotation += 2 * PI; //EDIT: Or + 360 if the atan2 function returns degrees instead of radians.
}

Edited by Lactose!

##### Share on other sites

Not to sound ungrateful here, in fact I'm going to study intensely all the code you all provided, and I am extremely grateful for all the information, but for the moment I'd like to stick to the tutorial code as much as possible so I can keep following it. I can't help but think that there must be a simpler way to do it.

In fact, I have noticed that in the line

rotation = atan2( targety , targetx ) * ( 180 / PI );

the " * ( 180 / PI ) " part  converts radians to degrees, meaning that all the calculations are done in degrees.

float current = rocket_sprite.getRotation();

also returns degrees, as I understand, so the only problem is the range.

I have tried calculating the current angle manually, using this code:

float current = atan2( rocket_sprite.getPosition().y , rocket_sprite.getPosition().x ) * ( 180 / PI );

As you might have guessed, it didn't make any difference. But I still think that there must be a solution along those lines with minimal changes to the tutorial code. I'm just not good enough at math to find it.

Still, I *do* appreciate immensely all the examples and information you provided, and I *will* study them. Just after I manage to finish the tutorial. :-)

So, if you are still willing to help me convert just the range of "getRotation()", I'm still open to suggestions. :-)

Edited by Kain5056

##### Share on other sites

When using atan, shouldn't you add 2*PI if angle is < 0, and keep as-is if not:

Yes, you are correct. I just fixed my previous code. Thanks for the tip! Edited by dejaime

##### Share on other sites

an API that uses degrees (which is a bad thing)

Yes, SFML has this problem. Hundreds of conversions needs to be made every frame which will in turn be converted back (to radians) in order to pass on to OpenGL.

Actually, glRotate also uses degrees, so maybe SFML and SDL are just trying to be transparent here and OpenGL is where the nonsense stems from. The only thing glRotate can possibly do with the angle is compute its sine and cosine. If it were up to me, OpenGL would allow you to pass in the sine and the cosine, and if we wanted to have a version that takes an angle, it would be in radians.

##### Share on other sites

After a bit of thought and some calculations, I discovered that the conversion of range from [0,360] to [180,-180] seems to be as simple as this:

float current = 180 - rocket_sprite.getRotation();

With this, the code should work just as in the ActionScript example, since now it's all in the same range and at the same units.

It does not. The missile goes shakey, and there's no easing.

I can't understand why.

I'll keep looking into it, but right now I'm baffled. Why does it work there, but not here?

For reference, HERE's the ActionScript tutorial. The example of how it should work is under "Step 10: Less Precision for Better Looks".

...And here is my current code:

#include <math.h>
#define PI 3.14159265

class rocket
{
private:
sf::Texture rocket_texture;
sf::Sprite rocket_sprite;
sf::Vector2f position;
float rotation;

public:
rocket();
void rocket_show( sf::RenderWindow * window );
void set_position( sf::Vector2f new_position );
void rocket_rotate( sf::RenderWindow * window );
void rocket_move();
};

rocket::rocket() { rotation = 0.f; }

{
rocket_sprite.setTexture( rocket_texture );

return true;
}

void rocket::rocket_show( sf::RenderWindow * window )
{
rocket_sprite.setOrigin( rocket_texture.getSize().x / 2 , rocket_texture.getSize().y / 2 );
rocket_sprite.setPosition( position );
window->draw( rocket_sprite );
}

void rocket::set_position( sf::Vector2f new_position ) { position = new_position; }

void rocket::rocket_rotate( sf::RenderWindow * window )
{
sf::Vector2i mouse_position = sf::Mouse::getPosition( *window );
float targetx = mouse_position.x - position.x;
float targety = mouse_position.y - position.y;
rotation = atan2( targety , targetx ) * ( 180 / PI );

int ease = 5;
float current = 180 - rocket_sprite.getRotation();

if( abs( rotation - current ) > 180 )
{
if( rotation > 0 && current < 0 ) rotation -= ( 360 - rotation + current ) / ease;
else if( current > 0 && rotation < 0 ) rotation += ( 360 - rotation + current ) / ease;
}
else if( rotation < current ) rotation -= abs( current - rotation ) / ease;
else rotation += abs( rotation - current ) / ease;

rocket_sprite.setRotation( rotation );
}

void rocket::rocket_move()
{
int speed = 5;
float speedx = 0;
float speedy = 0;
speedx = speed * ( 90 - abs( rotation ) ) / 90;
if( rotation < 0 ) speedy = -speed + abs( speedx );
else speedy = speed - abs( speedx );
position.x += speedx;
position.y += speedy;
}
`
Edited by Kain5056

##### Share on other sites

After a bit of thought and some calculations, I discovered that the conversion of range from [0,360] to [180,-180] seems to be as simple as this:
float current = 180 - rocket_sprite.getRotation();
With this, the code should work just as in the ActionScript example, since now it's all in the same range and at the same units.
It does not. The missile goes shakey, and there's no easing.

There are several aspects one needs to consider:

1.) Is the direction of 0° the same in AS and in SFML? E.g. does it mean straight to the right in both cases? Let us assume "yes".

2.) Is the rotational direction the same in AS and in SFML? E.g. does it mean counter-clockwise (or clockwise) in both cases? Let us assume "yes".

Then the half circle from 0° through +90° up to +180° is the same for both! There is no transformation needed. However, the other half of the circle is from +180° through 270° up to 360° in SFML and from -180° through -90° up to 0° in AS.

If you think of the periodicity of a circle, i.e. the same angle is reached when going 360° in any direction, the negative angles just go in the opposite rotational direction of the positive ones. So going 10° in the one direction is the same as going 360° minus those 10° in the other direction. That also means that it (should) make no difference whether you invoke setRotation with either -10° or +350°. As you can see, the difference of both is just 360°.

So why do we need to consider a transformation anyhow? Because the entire if-then-else block is written in a way that expects the angles being [0,+180] for the "upper" half circle and [-180,0] for the lower one.

So a transformation means that half of the values, namely those in the "upper" half-circle, are identity mapped (i.e. they need to be used as are), and only the other half of values, namely those of the "lower" half-cirlce, need actually to be changed. That is the reason several code snippets above, inclusive mine, use a stepwise transform that considers both halves of the circle separately.

It also means that the reverse transform, i.e. going back to the value space of SFML just before invoking setRotation, should not be required if SFML allows for negative angles, too. (I'm not sure about what SFML allows, so I suggested in my first post to do the reverse transform.)

Edited by haegarr

##### Share on other sites

Welp, no wonder my code does not work. You are right, it seems that SFML and ActionScript handle rotation a bit differently. I think that in ActionScript the missile points up at 90 degrees, but in SFML it points down.

All I need now to adjust the code it to find out how exactly does ActionScript handle rotation. Direction, degrees, and all that. Then, I'll be able to adjust the code accordingly. I'll try searching online tomorrow.

Thank you for explaining all this to me. :-)

##### Share on other sites

an API that uses degrees (which is a bad thing)

Yes, SFML has this problem. Hundreds of conversions needs to be made every frame which will in turn be converted back (to radians) in order to pass on to OpenGL.

Actually, glRotate also uses degrees, so maybe SFML and SDL are just trying to be transparent here and OpenGL is where the nonsense stems from. The only thing glRotate can possibly do with the angle is compute its sine and cosine. If it were up to me, OpenGL would allow you to pass in the sine and the cosine, and if we wanted to have a version that takes an angle, it would be in radians.

Well, glRotate belongs to the old transformation stack which is depracated, these days you can (and should) pass whatever it is you want to pass directly to the shader.