我需要一些关于p5js代码的帮助。我已经画了一个简单的草图,其中4个圆圈以给定的速度移动。我想要做的是当任何一个圆接触到另一个圆时,改变填充颜色。我认为问题是我在我的构造函数对象中初始化椭圆的x和y值,我需要随着圆的移动而更新它,但我不确定如何做到这一点。
// Declare objects
let bubble1;
let bubble2;
let bubble3;
let bubble4;
var centDistance;
function setup() {
createCanvas(windowWidth, windowHeight);
ellipseMode(CENTER);
// Create objects
bubble1 = new Bubble(50, 0, 2);
bubble2 = new Bubble(50, 2, 0);
bubble3 = new Bubble(50, -2, 0);
bubble4 = new Bubble(50, 0, -2);
}
function draw() {
background(0);
bubble1.display();
bubble2.display();
bubble1.move();
bubble2.move();
bubble3.display();
bubble3.move();
bubble4.display();
bubble4.move();
var d = dist(bubble1.x, bubble1.y, bubble2.x, bubble2.y);
if (d < bubble1.r+bubble2.r) {
bubble1.changeCol();
bubble2.changeCol();
}
}
class Bubble {
constructor(r, xSpeed, ySpeed) {
this.x = width/2;
this.y = height/2;
this.r = r;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.fillColor = color(255);
this.move = function () {
if (this.x>width/2+200 || this.x<width/2-200) {
this.xSpeed = -this.xSpeed;
}
if (this.y>height/2+200 || this.y<height/2-200) {
this.ySpeed = -this.ySpeed;
}
this.x += this.xSpeed;
this.y += this.ySpeed;
}
this.display = function() {
fill(this.fillColor);
stroke(255);
ellipse(this.x, this.y, 2*this.r);
}
this.changeCol = function () {
this.fillColor = color(0);
}
}
}发布于 2021-05-16 23:51:18
问题是,当动画开始时,两个圆发生碰撞,本例中为bubble1和bubble2。
然后,在changeCol函数中将颜色更改为黑色,这两个颜色都会变成黑色,然后一直保持不变。
你的代码工作正常,问题是this.fillColor不会在每次重新渲染时被重新初始化,因为你已经在setup函数中实例化了你的对象,所以当它们没有接触到其他圆时,你必须重新绘制它们。
if (d < bubble1.r+bubble2.r) {
bubble1.changeCol(255);
bubble2.changeCol(255);
} else {
bubble1.changeCol(0);
bubble2.changeCol(0);
}
this.changeCol = function (col) {
this.fillColor = color(col);
}https://stackoverflow.com/questions/67558015
复制相似问题