If I move the player right, left, up or down I move 5px in that direction. But if I press down and right for example player is moving 5px right and 5px down which is around 7 pixels from the previous position instead 5px.
I can add next IF statement: if (up and down) then spdX and spdY = (maxSpd - maxSpd√2) / or simple -25% ?.
But I think already my code is bit messy...

Any nice solutions which are fast and looks simple? :)
That is my code:
self.updateSpd = function(){
if(self.pressingRight){
self.spdX = self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdX += self.maxRun;
self.stamina --;
}
}
else if(self.pressingLeft){
self.spdX = -self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdX -= self.maxRun;
self.stamina --;
}
}
else{
self.spdX = 0;
}
if(self.pressingUp){
self.spdY = -self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdY -= self.maxRun;
self.stamina --;
}
}
else if(self.pressingDown){
self.spdY = self.maxSpd;
if(self.pressingShift && self.stamina > 0){
self.spdY += self.maxRun;
self.stamina --;
}
}
else{
self.spdY = 0;
}
}
You could make variables for X and Y direction with values -1, 0, 1:
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
Then adjust when moving diagonally:
if (dirX !== 0 && dirY !== 0) {
dirX *= Math.SQRT1_2;
dirY *= Math.SQRT1_2;
}
Then apply the rest:
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
All told:
self.updateSpd = function () {
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
if (dirX !== 0 && dirY !== 0) {
dirX *= Math.SQRT1_2;
dirY *= Math.SQRT1_2;
}
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
};
Or maybe:
self.updateSpd = function () {
var dirX = -self.pressingLeft + self.pressingRight;
var dirY = -self.pressingUp + self.pressingDown;
var speed = self.maxSpd;
if (self.pressingShift && self.stamina > 0 && (dirX !== 0 || dirY !== 0)) {
speed += self.maxRun;
self.stamina--;
}
if (dirX !== 0 && dirY !== 0) {
speed *= Math.SQRT1_2;
}
self.spdX = speed * dirX;
self.spdY = speed * dirY;
};
Note that this does behave differently from your original when both left and right are pressed (no movement, rather than moving right) or when both up and down are pressed (no movement, rather than moving up).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With