Isolate Movement

Hello everyone,

I am working on a game project which has a player sprite that moves using the WSAD keys. W and S move the player forwards and backwards while A and D rotate left and right. Below is the code I used to perform this.

class Player {
  float inputX, inputY, z, v;
  float inputW, inputH;
  float SPD = 2, ROT = .05;

  Player(float posX, float posY, float posW, float posH) {
    inputX = posX;
    inputY = posY;
    inputW = posW;
    inputH = posH;
  }

  void update() {
    v = (up? SPD : 0) - (down? SPD : 0);
    z += (right?  ROT : 0) - (left?  ROT : 0);

    if (inputX < 370 && cos(z) < 0 || inputX > 1550 && cos(z) > 0) {
      SPD = 0;
    } else {
      SPD = 2;
    }
    if (inputY < 50 && sin(z) < 0 || inputY > 600 && sin(z) > 0) {
      SPD = 0;
    }

    inputX +=  cos(z)*v;
    inputY +=  sin(z)*v;
  }

  void display() {
    translate(inputX, inputY);
    rotate(z);

    noStroke();
    fill(#008000); 
    rect(inputW/-2, inputH/-2, inputW, inputH);

    stroke(0);
    noFill();
    ellipse(10, 0, 5, 5);
  }
}

My problem is that I am trying to have the player character move "underneath" other objects on the map. Normally I would do this by placing the object lower in the programing, but when I do that with the code the translate(inputX, inputY) effects the objects as well and they move and rotate as the player does. How can I rewrite this code to only effect the player sprite?

Thank you for the help.

Answers

  • Answer ✓

    Use pushMatrix() and popMatrix(). Specifically, use pushMatrix() before your translate() and rotate() calls, and popMatrix() aftter you've drawn your player.

  • As always TfGuy44, that is very helpful. Thank you!

Sign In or Register to comment.