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

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - sakib_hasan63

Pages: [1]
1
Graphics / How to move sprite with keyboard?
« on: October 10, 2016, 04:17:12 pm »
I have started working on a simple game project. But I can't move the sprite  as it should be.Sprite is not moving at the right direction. It moves right even if I press 'left arrow' key. Please can anyone find out the problem. :)
here is the code :


#include<SFML/Graphics.hpp>
#include<iostream>
int W=900,H=600;

int main(){
    sf::RenderWindow window(sf::VideoMode(W,H),"My window");
    sf::Texture t1,t2;
    t1.loadFromFile("sprite1.png");
    t2.loadFromFile("bground.jpg");
    sf::Sprite s1,background;
    s1.setTexture(t1);
    background.setTexture(t2);
    //sf::Vector2i source(50,400);
    int direction=1,shiftX=10;


    while(window.isOpen()){
        sf::Event event;
        while(window.pollEvent(event)){
           switch(event.type){
                case sf::Event::Closed:
                    window.close();
                    break;
                    break;
                case sf::Event::KeyPressed:
                    if(event.key.code= sf::Keyboard::Left){
                         shiftX+=50;
                    }
                    else if(event.key.code= sf::Keyboard::Right){
                        shiftX-=50;
                    }
                    else if(event.key.code==sf::Keyboard::Up){
                        direction++;
                    }
                    else if(event.key.code==sf::Keyboard::Down){
                        direction--;
                    }
                    break;
            }

        }
        if(shiftX<0){
            shiftX=500;
        }
        else if(shiftX>500){
            shiftX=0;
        }
        if(direction>2){
            direction =0;
        }
        else if(direction<0){
            direction =2;
        }
        s1.setPosition(shiftX,400);
        sf::IntRect pos(200*direction,0,190,192);
        window.clear();
        s1.setTextureRect(pos);
        window.draw(background);
        window.draw(s1);
        window.display();
    }
}

Pages: [1]