我试图使用毕达哥拉斯定理使所有更接近指针的球体更暗。我不确定为什么我的mouseMoved无法正常工作。如果有人可以请查看我的代码,看看我的错误在哪里?
int numBalls = 100;
float spring = 0.17;
float gravity = 0;
float friction = -1;
float value = 255;
Ball[] balls = new Ball[numBalls];
void setup() {
size(500, 500);
for (int i = 0; i < numBalls; i++) {
balls[i] = new Ball(random(width), random(height), random(5, 60), i, balls);
}
noStroke();
fill(value);
}
void draw() {
background(0);
for (Ball ball : balls) {
ball.collide();
ball.move();
ball.display();
}
}
class Ball {
float x, y;
float diameter;
float vx = 0;
float vy = 0;
int id;
Ball[] others;
Ball(float xin, float yin, float din, int idin, Ball[] oin) {
x = xin;
y = yin;
diameter = din;
id = idin;
others = oin;
}
void collide() {
for (int i = id + 1; i < numBalls; i++) {
float dx = others[i].x - x;
float dy = others[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
float minDist = others[i].diameter/2 + diameter/2;
if (distance < minDist) {
float angle = atan2(dy, dx);
float targetX = x + cos(angle) * minDist;
float targetY = y + sin(angle) * minDist;
float ax = (targetX - others[i].x) * spring;
float ay = (targetY - others[i].y) * spring;
vx -= ax;
vy -= ay;
others[i].vx += ax;
others[i].vy += ay;
}
}
}
void move() {
vy += gravity;
x += vx;
y += vy;
if (x + diameter/15 > width) {
x = width - diameter/15;
vx *= friction;
}
else if (x - diameter/15 < 0) {
x = diameter/15;
vx *= friction;
}
if (y + diameter/15 > height) {
y = height - diameter/15;
vy *= friction;
}
else if (y - diameter/15 < 0) {
y = diameter/15;
vy *= friction;
}
}
void display() {
ellipse(x, y, diameter, diameter);
}
float d = sqrt((x - y) * (x - y) + (mouseX - mouseY) * (mouseX - mouseY) );
void mouseMoved () {
value = value - 85;
if (d < 75) {
fill (value);
}
}
}
答案 0 :(得分:1)
你犯了两个重大错误。第一个是关于定理它应该像这样计算:
sqrt((ball.x - mouseX) * (ball.x - mouseX) + (ball.y - mouseY) * (ball.y - mouseY))
第二个:如果你想使用鼠标事件,就不能在你的课堂内覆盖它们(你刚刚创建了一个名为mouseMoved
的自己的函数,它与mouse event无关。 )。要简单地覆盖它们,请将它放在草图末尾的任何类之外。此外,当您更改fill
值时,由于处理语言作为状态机的性质,它将影响所有球而不仅仅是关闭球(更多关于fill()
here)。
现在您可以删除mouseMoved()
,为了更好地理解,请在ball.display();
函数中添加此行代替draw
:
void draw() {
background(0);
for (Ball ball : balls) {
ball.collide();
ball.move();
float d = sqrt((ball.x - mouseX) * (ball.x - mouseX) + (ball.y - mouseY) * (ball.y - mouseY) );
if(d<75) ball.display();
}
}
希望它有所帮助,如果您有任何意见或问题,请点击此处。