I have a sprite that has to chase a moving target. I calculate the angle of the vector between target and the sprite.
The chasing object is created with a angle = -90;
In every frame I calculate the angle and I update the position this way
dx=0;
dy=0;
destination = spaceship.getSprite().getPosition();
angle = (float)(atan2((destination.y-sprite.getPosition().y), (destination.x-sprite.getPosition().x)));
if(sprite.getPosition().x != destination.x && sprite.getPosition().y != destination.y){
dx=(float)(cos(angle)*ALIEN_ACCEL);
dy=(float)(sin(angle)*ALIEN_ACCEL);
}
xPos += dx;
yPos += dy;
The draw method is written this way
sprite.setOrigin(sprite.getLocalBounds().width/2,sprite.getLocalBounds().height/2);
sprite.setPosition(xPos, yPos);
sprite.setRotation(angle+90);
gameWindow.draw(sprite);
The chasing object chase (sorry) well the target one, but it keeps the same angle, it never rotate, I mean, it follows the target but the rotation remains the same.
The target object, which is the player, rotate this way: if the left key is pressed it call a method that does angle -= bend_factor;
, while if the right key is pressed the method will do angle += bend_factor;
then the same draw method is called and the rotation is done well (both the player class and the chasing one extend the same class, so the draw method is the same.
What am I missing?
Have you tried something like this...
//helper function
template < typename T >
const T toDegrees ( const T degrees )
{
return degrees * ( 180 / PI );
}
//helper function
template <typename T>
const float getRotation ( T dx, T dy )
{
return toDegrees ( atan2 ( dy,dx ) ) + 180;
}
// rotate the sprite
void lookAtTarget(){
sf::Vector2f targetPos = getTarget()->getPosition();
sf::Vector2f enemyPos = m_enemy->getPosition();
float dx = enemyPos .x - targetPos .x;
float dy = enemyPos .y - targetPos .y;
m_enemy->setRotation( Math::getRotation( dx, dy ) );
}
Do you know about radians and degrees? Rotate I believe is the degrees relative to the sprite.
EDIT: Short little google: "Degrees measure angles by how far we tilted our heads. ... or angle in radians (theta) is arc length (s) divided by radius (r).
A circle has 360 degrees or 2pi radians — going all the way around is 2 * pi * r / r.
So a radian is about 360 /(2 * pi) or 57.3 degrees."
You can also check out the source code for the book "Beginning Game Programming in C++" which as an arena game, that accomplished this task very easy.