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

Processing Java模式下数组Bird对象点击检测报错求助

Processing游戏开发:点击所有Bird的功能实现与错误修复

错误原因

你遇到的x cannot be resolved or is not a field错误,是因为birds是Bird对象数组,不是单个Bird实例。数组本身没有x、y属性,必须通过数组索引(比如birds[i])访问数组里的每个Bird对象,才能获取其对应属性。

核心修改点

  1. 移除冗余单个Bird对象:已经用数组birds管理所有Bird,无需单独保留b对象。
  2. 将点击检测移至mousePressed函数:draw()每秒执行60次,放在这里会导致一次点击重复触发多次加分;mousePressed()仅在点击时执行一次,更适合处理点击逻辑。
  3. 给Bird类添加点击标记:增加isClicked属性,避免重复点击同一个Bird加分。
  4. 遍历数组检测每个Bird:点击时循环遍历所有Bird,判断鼠标是否点击到未被点击的Bird。
  5. 添加通关判断:检测所有Bird是否都被点击,触发下一关逻辑。

修改后的完整代码

Bird[] birds;
int score;
boolean isNextLevelReady;

void setup() {
  size(800, 600);
  score = 0;
  isNextLevelReady = false;
  initBirds(); // 初始化Bird数组
}

void draw() {
  background(200);
  
  // 显示所有Bird并更新状态
  for (int i = 0; i < birds.length; i++) {
    if (!birds[i].isClicked) { // 未被点击的Bird才移动
      birds[i].update();
    }
    birds[i].display();
  }
  
  // 显示鼠标提示
  fill(255, 0, 0, 100);
  ellipse(mouseX, mouseY, 10, 10);
  
  // 显示分数与通关提示
  fill(255);
  textSize(48);
  textAlign(LEFT);
  text("Score: " + score, 50, 50);
  
  if (isNextLevelReady) {
    textAlign(CENTER);
    text("点击进入下一关", width/2, height/2);
  }
}

void mousePressed() {
  if (isNextLevelReady) {
    // 重置进入下一关
    score = 0;
    isNextLevelReady = false;
    initBirds();
    return;
  }
  
  // 遍历所有Bird检测点击
  for (int i = 0; i < birds.length; i++) {
    Bird currentBird = birds[i];
    if (!currentBird.isClicked) { // 只检测未被点击的Bird
      float distance = dist(mouseX, mouseY, currentBird.x, currentBird.y);
      if (distance < currentBird.w/2) { // 用Bird的宽度一半作为判定范围
        currentBird.isClicked = true;
        score++;
        break; // 一次点击只加一次分
      }
    }
  }
  
  // 检查是否所有Bird都被点击
  isNextLevelReady = true;
  for (Bird bird : birds) {
    if (!bird.isClicked) {
      isNextLevelReady = false;
      break;
    }
  }
}

// 初始化Bird数组的封装函数
void initBirds() {
  birds = new Bird[4];
  for (int i = 0; i < birds.length; i++) {
    birds[i] = new Bird();
  }
}

class Bird {
  float x, y, w, h, vx, vy;
  boolean isClicked; // 标记是否被点击
  
  Bird() {
    x = -100;
    y = random(100, 500);
    w = 50;
    h = 50;
    vx = 2;
    vy = 0;
    isClicked = false;
  }
  
  void update() {
    x += random(0, 2)*vx;
    y += vy;
  }
  
  void display() {
    // 被点击的Bird改变颜色区分
    if (isClicked) {
      fill(100, 255, 100, 100);
    } else {
      fill(255, 255, 0, 100);
    }
    ellipse(x, y, w, h);
  }
}

关键说明

  • 点击判定范围:用currentBird.w/2(椭圆半径)作为距离阈值,比固定值25更适配Bird的大小。
  • 通关逻辑:点击完所有Bird后,显示通关提示,再次点击即可重置进入下一关。
  • 状态管理:isClicked属性确保每个Bird只能被点击一次,避免重复加分。

内容的提问来源于stack exchange,提问作者Malachi Williams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:12:49