我正在尝试为我必须为学校制作的游戏制作原型。但这并不好。我的问题是如何将变量从一个类导入到另一个类?我想要 playerX 和 Y 变量,所以我可以检查碰撞。这是用处理(Java)编写的。
如果有更好的检查碰撞的方法,请告诉我:) 我没有想法。提前致谢!
我的代码:
主班
Player thePlayer = new Player();
Guard theGuard = new Guard();
SpeedPWRUP speedPowerUp = new SpeedPWRUP();
void setup() {
  size(1000, 500);
  theGuard.init();
  thePlayer.init();
  speedPowerUp.init();
}
void updateGame() {
  theGuard.update();
  thePlayer.update();
  speedPowerUp.update();
}
void drawGame() {
  thePlayer.draw();
  theGuard.draw();
  speedPowerUp.draw();
  fill(color(255, 255, 255));
  text("Score:", 10, 20);
}
void draw() {
  background(255);
  fill (0, 0, 0);
  rect(-10, 401, 1100, 100);
  noFill();
  updateGame();
  drawGame();
}
警卫级
class Guard {
  public float guardX, guardY;
  float guardVX, guardVY;
  int fillColor;
  float guardHeight, guardWidth;
void init() {
   guardHeight = 80;
   guardWidth = 40;
   guardX = 300;
   guardY = 400-guardHeight;
   fillColor = color(255,0,0);
}
void update() {
  if (guardX == (random(width)-100)) 
    guardVX = 3;
  if (guardX == (random(width)+100)) 
    guardVX = -3;
  guardX += guardVX;
  guardY += guardVY;
}
void draw() {
  fill(fillColor);
  rect(guardX, guardY, guardWidth, guardHeight);
  noFill();
}
}
玩家等级
class Player {
  public float playerX, playerY;
  float vx, vy;
  int fillColor;
  float playerHeight, playerWidth;
  float jumpTime;
  float jumpHeight;
  boolean isJumping;
void init() {
  playerHeight = 80;
  playerWidth = 40;
  fillColor = color(0, 0, 0);
  jumpTime = 200;
  jumpHeight = 100;
  isJumping = false;
  playerX = 100;
  playerY = 400-playerHeight;
  vx = 0;
  vy = 0;
}
void update() {
  if (keyPressed) {
    if (key == 'a' || key == 'A') {
      vx = -2;
    }
  } else {
    vx = 0;
  }
  if (keyPressed) {
    if (key == 'd' || key == 'D') {
      vx = 2;
    }
  } else {
    vx = 0;
  }
  if (keyPressed) {
    if ((key == 'w' || key == 'W') && ( playerY > 400 - jumpHeight)) {
      isJumping = true;
    }
  } else {
    isJumping = false;
  }
  if (playerY < 400 - jumpHeight) {
  }
  if (keyPressed) {
    if (key == 's' || key == 'S') {
      playerHeight = 40;
    }
  } else {
    playerHeight = 80;
  }
  if(isJumping == true) {
    vy = -15;
  } else {
    vy = 0;
  }
  if (playerY < (400-playerHeight)) {
  vy = vy + 2.5;
  }
  playerX += vx;
  playerY += vy;
}
void draw() {
  fill(fillColor);
  rect(playerX, playerY, playerWidth, playerHeight);
  noFill();
}
}
加速功率类
class SpeedPWRUP {
  float diameter;
  public float pwrUpX, pwrUpY;
  int fillColor;
  void init() {
    diameter = 40;
    pwrUpX = 100;
    pwrUpY = 100;
    fillColor = color(0, 0, 255);
  }
  void update() {
    if (((playerX>pwrUpX) && (playerX < pwrUpX+diameter)) && (playerY > pwrUpY)&&(playerY>pwrUpY+diameter))
        end();
  }
  void draw() {
    fill(fillColor);
    ellipse(pwrUpX, pwrUpY, diameter, diameter);
    noFill();
  }
}