SFML community forums
Help => General => Topic started by: meto28 on March 09, 2011, 04:40:23 pm
-
Hi,
I'm doing a Snake game and I would like to know if there is a "clean" way to make it continue moving after pressing a key and not only at the press of the key
-
You could store the direction of the last key pressed and move your sprite in the according direction every frame.
-
You mean like this:
if (direction = "L")
{
Sprite.Move(-x, y);
}
if (direction = "U")
{
Sprite.Move(x, -y);
}
etc...
With Events instead of Input
Is that really a right way to do it ??
-
There is no "wrong" way. As long as you know what you're doing your code will probably be good (or at least understandable).
-
namespace SnakeDirection
{
enum Value
{
UP, DOWN, LEFT, RIGHT
};
}
// and then in your app class:
SnakeDirection::Value m_direction;
Then when you get a button press:
switch (key)
{
case sf::Key::Up:
m_direction = SnakeDirection::UP;
break;
case sf::Key::Left:
m_direction = SnakeDirection::LEFT;
break;
//etc
}
And in your update function:
switch (m_direction)
{
case SnakeDirection::LEFT:
//moveLeft
break;
case SnakeDirection::RIGHT:
//moveRight
break;
//etc
}
-
You can use the Input class to know whether a key is currently pressed. Obtain the Input instance with RenderWindow.GetInput().
-
You can use the Input class to know whether a key is currently pressed. Obtain the Input instance with RenderWindow.GetInput().
That's not what the OP wanted though:
"after pressing a key and not only at the press of the key"
:)
-
Thanks for your answers, now I have another issues.
I want my snake to always move on a distance of 1 tile
So I tried instead of Move the SetPosition but it still moving the same way (not "jumping" from a square to another)
The other one is that the snake only moves up or left if I use GetFrameTime:
if (direction == "D")
{
Sprite.SetPosition(X, Y);
Y += TileSize * ElapsedTime; //Doesn't work
}
if (direction == "U")
{
Sprite.SetPosition(X, Y);
Y -= TileSize * ElapsedTime; //Works
}
if (direction == "L")
{
Sprite.SetPosition(X, Y);
X -= TileSize * ElapsedTime; //Works
}
if (direction == "R")
{
Sprite.SetPosition(X, Y);
X += TileSize; //Works
}