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

Processing实现小行星移出屏幕/落地时红绿蓝循环变色问题咨询

解决方案

你的代码无法实现颜色循环的核心原因有两点:

  • 没有为每个小行星单独存储独立的颜色状态,所有小行星的填充色被硬编码为固定红色
  • 颜色切换逻辑没有绑定到「小行星碰撞地面/移出边界触发重置」的分支中

修改步骤

  • 新增全局整型数组colorIndex,为每个小行星单独记录当前颜色序号,约定0=红色、1=绿色、2=蓝色
  • 在setup()函数中初始化该数组,所有小行星初始颜色序号设为0(即初始为红色,和你现有效果一致)
  • 替换asteroidArr()中硬编码的fill(255, 0, 0),根据每个小行星当前的颜色序号动态设置填充色
  • 在小行星触发重置的判断分支内,更新对应小行星的颜色序号,通过对3取模实现红→绿→蓝的循环切换
  • 修复原有代码笔误:重置逻辑中speedY[i] = random(2, 2)会固定生成速度值2,改回原有的random(2, 3)即可保证下落速度随机

修改后完整可运行代码

float[] circleX;
float[] circleY;
float[] circledia;
float[] speedY;
float[] speedX;
// 新增:存储每个小行星的颜色索引
int[] colorIndex;
int asteroid = 10;

void setup()
{
    size(600, 700);
    background(188, 234, 255);

    circleX = new float[asteroid];
    circleY = new float[asteroid];
    circledia = new float[asteroid];
    speedX = new float[asteroid];
    speedY = new float[asteroid];
    colorIndex = new int[asteroid];

    for (int i = 0; i < asteroid; i++)
    {
        circleX[i] = random(50, 500);
        circleY[i] = 0;
        circledia[i] = random(10, 50);
        speedX[i] = random(-2, 2);
        speedY[i] = random(2, 3);
        // 初始颜色为红色(索引0)
        colorIndex[i] = 0;
    }
}

void draw()
{
    background(188, 234, 255);
    noStroke();
    fill(113, 69, 75);
    rect(0, 580, width, height);
    asteroidArr();
}

void asteroidArr()
{
    for (int i = 0; i < asteroid; i++)
    {
        noStroke();
        // 根据当前颜色索引设置填充色
        switch(colorIndex[i]) {
          case 0:
            fill(255, 0, 0);
            break;
          case 1:
            fill(0, 255, 0);
            break;
          case 2:
            fill(0, 0, 255);
            break;
        }
        ellipse(circleX[i], circleY[i], circledia[i], circledia[i]);
        circleY[i] = circleY[i] + speedY[i];
        circleX[i] = circleX[i] + speedX[i];

        if (circleY[i] > 560 || circleX[i] < -10 || circleX[i] > 610)
        {
            circleY[i] = 0;
            circleX[i] = random(50, 500);
            circledia[i] = random(10, 50);
            // 修复原笔误:random(2,2)固定返回2,改回随机速度
            speedY[i] = random(2, 3);
            speedX[i] = random(-2, 2);
            // 切换颜色,模3实现三色循环
            colorIndex[i] = (colorIndex[i] + 1) % 3;
        }
    }
}

逻辑说明:颜色更新放在重置分支内,每次小行星满足重置条件时才会切换到下一个颜色,重新从顶部下落时就会显示新的颜色,每个小行星的颜色循环完全独立,互不干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 11:06:16