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

Author Topic: [SFML 2.0] 2D diagonal movement problem  (Read 6383 times)

0 Members and 1 Guest are viewing this topic.

AltF4ToWin

  • Newbie
  • *
  • Posts: 11
    • View Profile
    • Email
[SFML 2.0] 2D diagonal movement problem
« 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);
}
 

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SFML 2.0] 2D diagonal movement problem
« Reply #1 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.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

 

anything