Hello everybody. I am writing a space game where the players has velocity and coasts along if nothing stops them. This has been working well but I now want to add a sort of speed limit, as the player can increase their speed to infinite amounts. I have used Unity mostly in the past, and in this situation I would just normalize the velocity vector and multiply it by the maximum allowed velocity. I have tried to implement something like this in SFML, but am running into a strange issue. The code performs as it should when the player ONLY has an X or Y velocity, but as soon as they have a little bit of both, the players X and Y velocity are both set to 0. I know I must be making a mistake in my code somewhere but cannot figure it out.
EDIT: Here is all the code on pastebin so it is formatted properly, it is also the entire class.https://pastebin.com/yUSpMSxEHere is my code for normalizing the velocity vectors.
void NormalizeVelocity(){
currentVelocity = fabs(velocityX) + fabs(velocityY);
if(currentVelocity > maxVelocity){
//percentage that each axis is the of the total velocity
int xp = fabs(velocityX) / (fabs(velocityX) + fabs(velocityY));
int yp = fabs(velocityY) / (fabs(velocityX) + fabs(velocityY));
//different normalization if value is negative
if(velocityX > 0){
velocityX = maxVelocity * xp;
}
else if(velocityX < 0){
velocityX = -maxVelocity * xp;
}
if(velocityY < 0){
velocityY = -maxVelocity * yp;
}
else if(velocityY > 0){
velocityY = maxVelocity * yp;
}
}
//player x and y position
x += velocityX;
y -= velocityY;
}
As I described before, the code works to limit the velocity if the player has no diagonal movement. As soon as there is some velocity on both X and Y, the players X and Y velocity are set back to 0. I will also post my input code below as it may be related to that as well.
void GetInput(){
//get keyboard input
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
AddYVelocity(.1);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
AddYVelocity(-.1);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
AddXVelocity(-.1);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
AddXVelocity(.1);
}
}
Any help would be appreciated. I have been pulling my hair out over this for the last hour or so. Also sorry about the code formatting, I tried to get it to look good in the quotes but it kept wanting to indent in random locations.