I
I
IliaNeverov2021-06-11 18:16:19
C++ / C#
IliaNeverov, 2021-06-11 18:16:19

How to do diagonal movement normally (sfml)?

Good day to all! Please tell me how to implement a normal "fair" diagonal movement?

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
    Sprite.move(0,-speed);
  }
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
    Sprite.move(-speed, 0);
  }
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
    Sprite.move(0, speed);
  }
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
    Sprite.move(speed, 0);
  }

When I press 2 buttons at the same time, for example, s and d, the sprite moves a greater distance than it should, tell me how to do it normally so that when you press the same s and d, the sprite moves normally

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-06-11
@IliaNeverov

Read the velocity vector and then divide by its length. Depending on the buttons pressed, add or subtract speed from vx or vy (which are initially 0). Then, after checks, divide both numbers by sqrt(vx*vx+vy*vy)(if it's not 0) and shift the sprite by vx, vy.
Can be optimized - add 1/-1 instead of speed. Then the value vx*vx+vy*vycan only be 0,1 or 2. Get a constant array kScaleCoef[3] = {1, 1, sqrt(2)}and then do

Sprite.Move(speed/kScaleCoef[vx*vx+vy*vy]*vx, speed/kScaleCoef[vx*vx+vy*vy]*vy);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question