Processing程序中初始白色网格圆形为何全部显示为黑色?
问题排查与修复方案
我帮你找出了代码里的几个核心问题,这就是为什么你会看到全黑网格和奇怪小白点的原因,咱们一步步来解决:
1. 颜色数组初始化错误
你用了增强for循环for(int i:pointColour)来初始化数组,这里的i是数组元素的当前值,而不是索引。Processing里color数组默认初始值是0(也就是黑色),所以这个循环实际上一直在给pointColour[0]赋值为白色,剩下的23个元素还是默认的黑色——这就是程序一启动就显示全黑网格的根源。
修复方法:换成普通的索引循环,遍历每个数组索引来赋值:
for(int i = 0; i < pointColour.length; i++){ pointColour[i] = white; }
2. 圆形绘制位置未重置
在draw()的圆形绘制循环里,你用的是全局变量pointX和pointY,每次draw()调用时,这两个变量会在上一次的基础上继续累加,导致圆形位置越来越偏,甚至超出画布,那个奇怪的小白点就是位置溢出后显示的异常图形。
修复方法:在绘制循环开始前,把位置变量重置为初始值,最好换成局部变量,避免全局变量污染:
// 把全局的pointX、pointY换成循环内的局部变量,每次循环都从初始位置开始 int pointX = pointIntervX; int pointY = pointIntervY; for(int i = 0;i<24;i++){ pointMaker(pointColour[i], pointX, pointY); pointX += pointIntervX; if(pointX > pointIntervX*4){ pointX = pointIntervX; pointY += pointIntervY; } }
3. 背景未刷新
draw()函数里没有每次刷新背景,导致锤子和圆形的绘制会留下轨迹,影响视觉效果,也会干扰你观察圆形的状态。
修复方法:在draw()的最开头添加background(255);,清除上一帧的所有内容。
4. 额外:实现锤子到底部时的圆形变色逻辑
你提到需要锤子到达底部时依次变色,我帮你加了一个currentPointIndex变量来追踪当前要变色的圆形,在锤子重置位置的逻辑里添加变色代码。
修复后的完整代码
int hammerPos = 0; int hammerVel = 1; int hammerPending = 0; int jump = 60; int pointIntervX = 20; int pointIntervY = 20; int pointSize = 10; color white = color(255,255,255); color black = color(0,0,0); color red = color(255,0,0); color[] pointColour = new color[24]; int currentPointIndex = 0; // 追踪需要变色的圆形索引 // 绘制单个圆形的方法 void pointMaker(color colour, int pointX, int pointY){ fill(colour); noStroke(); // 去掉描边,让圆形更干净(不需要可以删掉) ellipse(pointX,pointY,pointSize,pointSize); } void setup(){ size(200,200); background(255); // 正确初始化所有圆形为白色 for(int i = 0; i < pointColour.length; i++){ pointColour[i] = white; } } void draw(){ background(255); // 每次刷新背景,清除上一帧轨迹 // 绘制锤子 fill(0); stroke(0); strokeWeight(6); line(128,hammerPos+10,148,hammerPos-12); strokeWeight(4); line(125,hammerPos+13,129,hammerPos+11); strokeWeight(8); line(115,hammerPos+5,130,hammerPos+20); // 更新锤子位置 hammerPending += hammerVel; if (hammerPending > jump){ hammerPos += hammerPending; hammerPending = 0; } // 重置圆形绘制的起始位置,用局部变量避免全局污染 int pointX = pointIntervX; int pointY = pointIntervY; // 绘制24个圆形网格 for(int i = 0;i<24;i++){ pointMaker(pointColour[i], pointX, pointY); pointX += pointIntervX; if(pointX > pointIntervX*4){ pointX = pointIntervX; pointY += pointIntervY; } } // 锤子到达底部时的逻辑:重置位置 + 依次变色圆形 if(hammerPos > height){ hammerPos = 0; // 确保不超过数组长度 if(currentPointIndex < pointColour.length){ pointColour[currentPointIndex] = red; currentPointIndex++; } } }
现在运行这段代码,初始时圆形会和白色背景融为一体(隐藏状态),每次锤子落到屏幕底部,就会从左到右、从上到下依次把圆形变成红色,完全符合你的需求啦。
内容的提问来源于stack exchange,提问作者A.Lopez
相关产品推荐
相关产品推荐

