So I’m working on a movement script for a game, but when I go from diagonal to just one direction, it continues moving diagonally.
PImage pS[]; //Allocating a spot for Player sprites
Player p; //Creates the player
//Keyboard inputs
boolean up;
boolean down;
boolean left;
boolean right;
boolean run;
//End keyboard inputs
void setup() {
size(1024, 896);
background(0);
p = new Player();
up = false;
down = false;
left = false;
right = false;
}
void draw() {
background(0);
p.move();
p.show();
}
class Player {
PVector pos;
PVector vel;
PVector acc;
int max;
Player() {
pos = new PVector(0, 192);
vel = new PVector();
acc = new PVector();
max = 3;
}
void show() {
rect(pos.x,pos.y,40,40);
}
void move() {
if (up||down||left||right) {
if (up) {
acc.y = -0.1;
} else if (down) {
acc.y = 0.1;
}
if (left) {
acc.x = -0.1;
} else if (right) {
acc.x = 0.1;
}
if (run) {
max=5;
} else {
max=3;
}
vel = PVector.add(acc,vel);
} else {
acc.x = 0;
acc.y = 0;
vel = PVector.div(vel, 1.1);
}
vel.limit(max);
pos = PVector.add(pos,vel);
}
}
class Camera {
}
void keyPressed() {
if (key=='w') {
up=true;
} else if (key=='s') {
down=true;
}
if (key=='a') {
left=true;
} else if (key=='d') {
right=true;
}
if (key==CODED) {
if (keyCode==SHIFT) {
run=true;
}
}
}
void keyReleased() {
if (key=='w') {
up=false;
} else if (key=='s') {
down=false;
}
if (key=='a') {
left=false;
} else if (key=='d') {
right=false;
}
if (key==CODED) {
if (keyCode==SHIFT) {
run=false;
}
}
}
If there’s a better way to do this, let me know.