Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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*vy
can 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 questionAsk a Question
731 491 924 answers to any question