刚入门processing,大家能不能看一下,为啥球碰到线不会变色啊,感激不尽!
int linex[];
float liney[];
color c;
int time;
float speed;
int x;
int y;
boolean timemove;
float g[];
boolean move;
color c2;
void setup() {
size(600, 600);
time=width;
x=50;
c=120;
timemove=false;
move=false;
y=height-100;
liney=new float[5];
for (int i=0; i<liney.length; i++) {
liney[i]=random(height/2, height/2+height/4);
}
}
void draw() {
background(255);
speed=1;
linex=new int[5];
g = new float[linex.length];
for (int i=0; i<linex.length; i++) {
stroke(255, 0, 0);
strokeWeight(3);
linex[i]=width/6*i;
line(40+linex[i], 0, 40+linex[i], liney[i]);
line(40+linex[i]+50, height-30, 40+linex[i]+50, height-liney[i]-30);
line(0, height-30, width, height-30);
if (x>=40+linex[i]-30/2 && x<+40+linex[i]+30/2 && y>0 && y<liney[i]+30/2
||x>=40+linex[i]+50-30/2 && x>=40+linex[i]+50+30/2 && y>height-30 && y<height-liney[i]-30) {
c=color(255, 0, 0);
c2=color(255, 0, 0);
speed=2;
} else {
c=120;
c2=color(#8BFF8C);
}
}
noStroke();
fill(c);
ellipse(x, y, 30, 30);
fill(#8BFF8C);
stroke(c2);
rect(width/6*5-10, width/6*5-30, width/6+10, width/6);
noStroke();
if (timemove) {
fill(0, 0, 220);
rect(0, height-30, time, 30);
time-=speed;
}
}
void mouseDragged() {
timemove=true;
float e=dist(mouseX, mouseY, x, y);
if (e<=30/2) {
x=mouseX;
y=mouseY;
}
}
在你的代码中,主要问题在于碰撞检测部分("collision detection")。你判断球是否与线相交的条件不正确。另外,你的条件判断时候,把两个 &&
错误地写成了 ||
,应该把这些判断条件分开。
以下是改正后的判断条件:
if ((x>=40+linex[i]-30/2 && x<=40+linex[i]+30/2 && y>=0 && y<=liney[i])
|| (x>=40+linex[i]+50-30/2 && x<=40+linex[i]+50+30/2 && y>=height-liney[i]-30 && y<=height-30)) {
另外,不建议在 draw()
函数内部频繁创建新的数组,这会增加内存压力和减慢程序运行速度。在这个例子中,linex
和 g
数组应该在 setup()
函数内部初始化,并在 draw()
函数内部更新。
// at the top of your code
linex = new int[5];
g = new float[linex.length];
// inside setup function
for (int i = 0; i < linex.length; i++) {
linex[i] = width/6*i;
}
// inside draw function, replace linex[i] = width/6*i with following
linex[i] = (width/6*i + frameCount) % width;
我假设你希望线随时间的推移而移动。如果不是,你可以忽略上面的修改建议。