Followers 0

# Homing missile problem

## 24 posts in this topic

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. :-)

Edited by Kain5056
2

##### Share on other sites

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

0

##### 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...

0

##### 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

0

##### Share on other sites

*mindblown by Alvaro's code*

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

0

##### Share on other sites

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...
0

##### Share on other sites

My highschool taught me matrices but not that.

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

0

##### 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.

1

##### 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
0

##### 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:
* 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.
2

##### 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
2

##### 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
0

##### 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
1

##### 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.
1

##### 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
0

##### 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
1

##### 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. :-)

0

##### 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.

1

## Create an account

Register a new account