SFML community forums

Help => Window => Topic started by: AltF4ToWin on May 17, 2013, 06:52:15 pm

Title: [SFML 2.0] 2D diagonal movement problem
Post by: AltF4ToWin on May 17, 2013, 06:52:15 pm
Minor question that is probably me being a huge derp, but nevertheless I am momentarily stumped.

Basically, I'm trying to implement 2D movement, which works fine, however when I try to move diagonally, the sprite faces the right direction, but its coords don't change and it doesn't move.

if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)&&sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
   Ship_s.setRotation(135.f);
   Ship_s.move(7, 7);
}
 
Title: Re: [SFML 2.0] 2D diagonal movement problem
Post by: Nexus on May 18, 2013, 12:14:41 pm
Don't do it like this. You should rather check for the four main directions, and add their contributions to a velocity vector.
const float speed = ...;
sf::Vector2f v;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    v.y -= speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    v.y += speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    v.x -= speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    v.x += speed;

Then, you can still address the problem that diagonal movement leads to a higher speed, just divide by the square root of 2 in this case.
if (v.x != 0.f && v.y != 0.f)
    v /= std::sqrt(2.f);

The object is eventually moved by an offset which equals to the velocity multiplied with the passed time.
sf::Time dt = ...;
object.move(v * dt.asSeconds());

To compute the angle, you can use std::atan2(). Please refer to www.cppreference.com for more details.