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

Author Topic: Question about sprite moving  (Read 1997 times)

0 Members and 1 Guest are viewing this topic.

mnajrg

  • Newbie
  • *
  • Posts: 26
    • View Profile
Question about sprite moving
« on: August 10, 2013, 10:27:07 am »
I can keep the sprite on the screen, but my problem is when it reaches the end of screen, it cant go back left, And if I continue pressing key it lefts the screen.
Quote
#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow Window(sf::VideoMode(320,320),"");
    sf::Texture tex;
    tex.loadFromFile("bullet.png");
    sf::Sprite sprite(tex);
    float movespeed = 0.1f;
    float velocityX = 0;
    while(Window.isOpen())
    {
        Window.clear();
        Window.draw(sprite);
        Window.display();
        sf::Event Event;
        while(Window.pollEvent(Event))
        {
            switch(Event.type)
            {
            case sf::Event::Closed:
                Window.close();
            }
        }
        if(sprite.getPosition().x + 9 > 320 || sprite.getPosition().x < 0)
            velocityX = 0;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            velocityX = movespeed;
            sprite.move(velocityX,0);
        }
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            velocityX = -movespeed;
            sprite.move(velocityX,0);
        }
    }
}

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: Question about sprite moving
« Reply #1 on: August 10, 2013, 12:00:09 pm »
When I run that code nothing stops the sprite from leaving the screen. Are you sure you copied the code exactly? It seems like the if(sf::Keyboard::isKeyPressed... blocks should be contained inside the if(sprite.getPosition()... block, or else the velocityX = 0; statement doesn't actually stop it from moving.

But that aside, the problem is fairly simple.  You just need to think about what's going on at the bottom of your code some more.  At the moment, when the bullet is at either edge of the screen, you tell it to not move at all (velocityX = 0;).  What you actually want is to let it move in one direction only.  So what you probably should do is something like this:

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            velocityX = movespeed;
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            velocityX = -movespeed;

        if(sprite.getPosition().x + 9 > 320 && velocityX > 0) //if on right edge and trying to move right, don't let it move
            velocityX = 0;
        if(sprite.getPosition().x < 0 && velocityX < 0) //if on left edge and trying to move left, don't let it move
            velocityX = 0;
               
                //now that we've done that check, actually move it
        sprite.move(velocityX,0);
 
« Last Edit: August 10, 2013, 12:08:25 pm by Ixrec »