• 11
• 9
• 10
• 9
• 10

# How to make an sprite go to correct direction

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

## Recommended Posts

Hi,

On my game i want that my shoot go to correct direction (enemy direction), but it doesnt occur.

You can see here:

The code that im using is (on update):

void Bullet::update(){	updateSpriteDirection();	checkCollision();		updatePosition();}void Bullet::updateSpriteDirection() {	sprite.SetRotation( Functions::angle(sprite.GetPosition().x, sprite.GetPosition().y, targetX, targetY) );}void Bullet::checkCollision(){	if (sprite.GetPosition().x + sprite.GetSize().x < 0)	{		remove();	}	else if (sprite.GetPosition().y + sprite.GetSize().y < 0)	{		remove();	}	else if (sprite.GetPosition().x > Constants::SCREEN_WIDTH)	{		remove();	}	else if (sprite.GetPosition().y > Constants::SCREEN_HEIGHT)	{		remove();	}}void Bullet::updatePosition(){	sprite.SetPosition(sprite.GetPosition().x + speedX, sprite.GetPosition().y + speedY);}void Bullet::updateSpeed(){	if (sprite.GetPosition().x < targetX)	{		speedX = Constants::BULLET_SPEED;	}	if (sprite.GetPosition().x > targetX)	{		speedX = (Constants::BULLET_SPEED * -1);	}	if (sprite.GetPosition().y < targetY)	{		speedY = Constants::BULLET_SPEED;	}	if (sprite.GetPosition().y > targetY)	{		speedY = (Constants::BULLET_SPEED * -1);	}}

What is wrong?

Im using SFML.

##### Share on other sites
I see you found an angle to point the texture in the (presumably) correct direction, but you never use that angle for the direction of the velocity. Since you want the bullet to move along that angle, you can use trigonometry to find how much you need to move on each axis, each frame. Lets say the amount the bullet needs to move each frame is (x, y), the speed of the bullet is s, and the angle is A, so using primary trig ratios cos(A) = x/s, therefore x = s * cos(A). Similarly, sin(A) = y/s, therefore y = s * sin(A). Using this you need to set the velocity, something like

// I am assuming sprite has a GetRotation method
speedX = Constants::BULLET_SPEED * cos(sprite.GetRotation());
speedY = Constants::BULLET_SPEED * sin(sprite.GetRotation());

Hope that helps.