You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用if/then语句实现碰撞时分数计数器仅更新一次?

解决碰撞持续触发分数累加的问题

你的核心问题是:只要两个角色处于碰撞状态,每一次draw()循环都会执行分数累加逻辑,导致分数持续上涨。要解决这个问题,关键是只在碰撞发生的第一帧加分,而不是每帧都加。

具体实现步骤

  • 添加一个全局布尔变量,记录当前是否处于碰撞状态,用来区分「首次碰撞」和「持续碰撞」
  • 在碰撞检测逻辑中,只有当「当前处于碰撞状态,但上一帧未碰撞」时,才执行分数累加
  • 同步更新碰撞状态变量,确保状态准确

修改后的完整代码

int player1PosX = 32;
int player1PosY = 30;

int player2PosX = 608;
int player2PosY = 570;

int scoreCounter = 0; // 修正原变量名不一致的问题
boolean isColliding = false; // 新增:记录当前碰撞状态

void draw() {
  drawPlayingField();
  drawPlayers();
  drawScoreBar();
  isTagged(player1PosX, player1PosY, player2PosX, player2PosY);
}

void isTagged(int p1X, int p1Y, int p2X, int p2Y) {
  println(p1X, p1Y, p2X, p2Y);
  // 判断当前是否碰撞
  boolean currentCollision = (p1X == p2X && p1Y == p2Y);
  
  if (currentCollision) {
    text("Tag, you're it!", 225, 300);
    // 只有从非碰撞变为碰撞时,才加分
    if (!isColliding) {
      scoreCounter += 1;
    }
  }
  // 更新碰撞状态,同步到全局变量
  isColliding = currentCollision;
}

额外说明

  • 原代码中scoreCountCount和scoreCounter变量名不一致,已经统一为scoreCounter,避免编译错误
  • 如果你是检测矩形/圆形碰撞(而非精确坐标相等),只需要把currentCollision的判断逻辑换成对应的碰撞检测公式即可,状态判断的逻辑保持不变

内容的提问来源于stack exchange,提问作者Max Blowers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:46:05