Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to move a sprite in a fixed range?  (Read 1007 times)

0 Members and 1 Guest are viewing this topic.

Iloveolaf

  • Newbie
  • *
  • Posts: 2
    • View Profile
How to move a sprite in a fixed range?
« on: January 05, 2020, 05:39:43 am »
I'm not a native English speaker, so sorry for my poor English in advance. :'(

I want to move a sprite, where it's y-coordinate will go from 0 to 352 and from 352 to 0 repeatedly.

But I don't know how to write it.

This is my code now. And it'll like from 0 to 352 go back to 0 and from 0 to 352.

Code: [Select]
int main(){

while (window.isOpen()) {

                sprite.move(0.f, 0.0001f * elapsed.asMicroseconds());
                clock.restart();
                if (sprite.getPosition().y >= 352) {
                     do {
                          sprite.move(0.f, -0.0001f * elapsed.asMicroseconds());
                          clock.restart();
                     } while (sprite.getPosition().y >= 0);
                }
window.draw(sprite);
window.display();
}
}

Can anyone give me some tips how to write it? Thanks!
« Last Edit: January 05, 2020, 05:58:11 am by Iloveolaf »

fallahn

  • Sr. Member
  • ****
  • Posts: 492
  • Buns.
    • View Profile
    • Trederia
Re: How to move a sprite in a fixed range?
« Reply #1 on: January 05, 2020, 11:48:31 am »
You can do this by adding a velocity property which dictates the speed and direction of your sprite.

struct MyThing final
{
    sf::Sprite sprite;
    sf::Vector2f velocity;
};
 

Set the velocity y value (the direction you want to move) to a certain amount, eg: 10 which will be the number of units it moves per second. Move the sprite by this velocity multiplied by the elapsed time:

while(window.isOpen())
{
    //handle events here

    sf::Time elapsed = clock.restart();

    myThing.sprite.move(myThing.velocity * elapsed.asSeconds());

    window.clear();
    window.draw(myThing.sprite);
    window.display();
}
 

This will move the sprite in a straight line as defined by the velocity. To make it change direction add a position check after the sprite has moved:

auto position = myThing.sprite.getPosition();
if (position.y < 0)
{
    //clamp the position to the bounds
    position.y = 0;
    myThing.sprite.setPosition(position);

    //reverse the direction
    myThing.velocity.y = -myThing.velocity.y;
}
else if (position.y > 352)
{
    //see above
}
 

This post offers a more detailed explanation: https://medium.com/@swiftsnippets/vectors-position-velocity-and-direction-b85342ed9e3a

Iloveolaf

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: How to move a sprite in a fixed range?
« Reply #2 on: January 06, 2020, 01:30:07 am »
Thanks I'll try!