Smooth keyboard movement

Hello, I'm trying to make a simple coded game, starting with the movements. the objects moves just fine but I guess this problem is common where the object's movement stutters when changing directions especially when you are pressing both buttons at once

Code:

square p;

int squareX = 172, squareY = 164;


void setup() {
  size(400, 400);
  frameRate(64);
  p = new square();
}

void draw() {
  background(250, 245, 200);
  p.squareSprite();
  p.squareMove();
  p.collision();
}


class square {
  void squareSprite() {
    fill(200, 180, 190);
    strokeWeight(2);
    stroke(204, 184, 194);
    rect(squareX, squareY, 50, 50, 4);
  }

  void squareMove() {
    if (keyPressed== true) {
      if (key == 'w') {squareY-= 4;}
      if (key == 'a') {squareX-= 4;}
      if (key == 's') {squareY+= 4;}
      if (key == 'd') {squareX+= 4;}
    }
  }
  void collision(){
      if(squareX >= 350) {squareX = 350;}
      if(squareX <= 0) {squareX = 0;}
      if(squareY >= 350) {squareY = 350;}
      if(squareY <= 0) {squareY = 0;}
  }
}
Tagged:
Sign In or Register to comment.