SFML community forums

Help => Graphics => Topic started by: dd on November 09, 2023, 06:40:02 pm

Title: Moving sprite forward (moving it in the direction of it's rotation)
Post by: dd on November 09, 2023, 06:40:02 pm
Hi, I'm trying to develop a rougelike game using SFML, and in said game I have a blaster.
I've read the documentation, but I can't figure out for the life of me how to move a sprite in it's pointed direction.
I would really appreciate it if you could tell me how to do this.

Thank you for your time.
Title: Re: Moving sprite forward (moving it in the direction of it's rotation)
Post by: Hapax on November 09, 2023, 10:05:35 pm
To move a sprite, we can use:
sprite.move(v);
where v is a 2D vector representing movement in 2D space.
Usually, this is thought of as x and y so the vector would be an x offset and a y offset.

SFML provides a 2D vector class called sf::Vector2f that is the type passed to sprite.move()

To calculate the x and y offsets, we need to use sine and cosine as usual based on the angle (https://www.google.com/search?q=calculate+x+and+y+from+angle+and+distance&oq=calculate+x+and+y+from+angle) you want to move.

However, if you are using the current SFML 3, an sf::Vector2f can work with angles directly (so calculates the sine/cosine stuff automatically).
Title: Re: Moving sprite forward (moving it in the direction of it's rotation)
Post by: dd on November 09, 2023, 11:05:24 pm
It worked perfectly. Thank you a lot.