由于某些原因,当我运行下面的代码时......角色只会沿着对角线向下移动。让我们说第一行"绘图是字符:
\
\
\
\
\
如果我按向上,向右,向下或向左键,它是唯一的移动方向!
请帮忙,我想向右走,向上走,如果向上走,向下走,如果向下,向左走,如果离开。
我的代码是:
#include<iostream>
#include<string>
#include<SFML\Graphics.hpp>
using std::cout;
using std::endl;
enum Direction
{
DOWN,
LEFT,
RIGHT,
UP
};
int main()
{
sf::RenderWindow _Win(sf::VideoMode(600, 600), "Hello World");
sf::Texture _texture;
if (!(_texture.loadFromFile("Resources/SPRITE.png")))
{
cout << "Could not load iamge" << endl;
}
//Source, tell us our starting position.
//Vector2i = Vector of 2 in SFML
sf::Vector2i source(1, DOWN/*or 0*/);
sf::Sprite _sprite(_texture);
float x = _sprite.getPosition().x;
float y = _sprite.getPosition().y;
while (true)
{
sf::Event _event;
while (_Win.pollEvent(_event))
{
switch (_event.type)
{
case sf::Event::Closed:
_Win.close();
exit(1);
break;
case sf::Event::KeyPressed:
switch (_event.key.code)
{
case sf::Keyboard::Up:
source.y = UP;
_sprite.move(sf::Vector2f(x,y--));
y = 3, x=3;
break;
case sf::Keyboard::Down:
source.y = DOWN;
_sprite.move(sf::Vector2f(x, y++));
y = 3, x = 3;
break;
case sf::Keyboard::Right:
source.y = RIGHT;
_sprite.move(sf::Vector2f(x++, y));
y = 3, x = 3;
break;
case sf::Keyboard::Left:
source.y = LEFT;
_sprite.move(sf::Vector2f(x--, y));
y = 3, x = 3;
break;
}
break;
}
}
//Cropping Out Image
//Please Look at sprite in resources/Sprite.png
//When we run this :
//_sprite.setTextureRect(sf::IntRect( source.x*32 , source.y*32 , 32 , 32 ));
//Its going to give us the top left corner sprite image. Thats so because
//we are cropping source.x*32 , which of 32 is the width of the sprite.. So it
//starts from 1 * 32. 32 is the width of one sprite so it goes to the end of it.
//Same Applies to the y. source.y * 32. It just goes to the end of the down sprite.
//As you go down the y increases, 1 * 32 = 32. And 32 is the width of one sprite
//so it shows body of one full sprite.
_sprite.setTextureRect(sf::IntRect( source.x*32 , source.y*32 , 32 , 32 ));
//Clears Window(Flickering..)
_Win.clear();
//Draw Sprite
_Win.draw(_sprite);
//And Finally Display the Window.
_Win.display();
}
}
答案 0 :(得分:1)
在switch语句的每种情况下,都将精灵移动(x,y),然后根据方向递增或递减x或y。然而,这是徒劳的,因为在下一行,你将它们都重置为3.所以实际上,无论方向键被按下,你都这样做:
_sprite.move(sf::Vector2f(3, 3));
即右侧3个单位,3个单位向下,这似乎符合您所看到的运动描述。我不确定你会采取什么样的动作,但这是一个可行的例子:
switch (_event.key.code) {
case sf::Keyboard::Up:
_sprite.move(sf::Vector2f(0, -3));
break;
case sf::Keyboard::Down:
_sprite.move(sf::Vector2f(0, 3));
break;
case sf::Keyboard::Right:
_sprite.move(sf::Vector2f(3, 0));
break;
case sf::Keyboard::Left:
_sprite.move(sf::Vector2f(-3, 0));
break;
}
每次按下方向键时,这将移动精灵3个单位。