SFML community forums
Help => Window => Topic started by: dotty on February 20, 2012, 05:13:20 pm
-
Hello, I read here a couple of days ago about using a Vector2f to process my movement, this seemed an obvious thing once I read it. However, I'm getting a little confused by it.
I have an Update() method which gets run every frame, I also have a ManageInput() method as well, which also get's run every frame.
The Update() method also runs this code
this->shape.Move( this->velocity );
this->velocity is obviously the Vector2f in question. The ManageInput() method is just a series of IF statements checking for W,A,S and D keyPresses. Here's a sample of this code
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::W )) {
this->velocity = sf::Vector2f(0, -1) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::S )) {
this->velocity = sf::Vector2f(0, 1) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::A )) {
this->velocity = sf::Vector2f(-1, 0) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::D )) {
this->velocity = sf::Vector2f(1, 0) * this->deltatime;
}
However, using this code I can only move along 1 axis at a time.
If I modify this code to look like this
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::W )) {
this->shape.Move(sf::Vector2f(0, -1)) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::S )) {
this->shape.Move(sf::Vector2f(0, 1)) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::A )) {
this->shape.Move(sf::Vector2f(-1, 0)) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::D )) {
this->shape.Move(sf::Vector2f(1, 0)) * this->deltatime;
}
It works as expected, allows me to both on both axis. How would I modify the top code to work as I want it to.
-
try
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::W )) {
this->velocity += ( sf::Vector2f(0, -1) * this->deltatime );
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::S )) {
this->velocity += sf::Vector2f(0, 1) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::A )) {
this->velocity += sf::Vector2f(-1, 0) * this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::D )) {
this->velocity += sf::Vector2f(1, 0) * this->deltatime;
}
-
Hello,
this because you're using sf::Events instead of sf::Input (if you're on SFM-1.6).
Read this Tutorial (http://www.sfml-dev.org/tutorials/1.6/window-events.php)for more explanations.
Edit : oops, sorry :D did'nt wrote until the end... Elgan is right ;) (you delete your first assignement with both "=" operations).
-
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::W )) {
this->velocity.y -= this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::S )) {
this->velocity.y += this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::A )) {
this->velocity.x -= this->deltatime;
}
if (sf::Keyboard::IsKeyPressed( sf::Keyboard::D )) {
this->velocity.x += this->deltatime;
}