[英]P5.js change stroke of object instance stored in array affects wrong instance
如果我點擊第一個球,第二個顯示為已選擇。 如果我點擊第二個,第三個顯示為選中狀態,依此類推。
但是布爾值設置正確。
我在代碼中找不到問題,應該是一些邏輯錯誤。
我感謝任何幫助,謝謝。
享受這個悖論的樂趣;)
我的 Sketch.js
let balls = [];
let ballAmount = 3;
function setup() {
let red = color(255, 0, 0);
let green = color(0,255,0);
let blue = color(0,0,255);
let colors = [red, green, blue];
createCanvas(innerWidth, innerHeight);
noStroke();
for (let i = 0; i < ballAmount; i++) {
let tempX = 200 + (100 * i);
balls.push(new Ball(tempX, 200, 20, colors[i]));
}
}
function draw() {
background(0);
balls.forEach((ball) => {
ball.show();
});
}
function mousePressed() {
print(balls);
balls.forEach((ball) => {
ball.clicked();
});
}
我的 ball.js(類)
class Ball {
constructor(x, y, r, color){
this.pos = new p5.Vector();
this.pos.x = x;
this.pos.y = y;
this.r = r;
this.isSelected = false;
this.ballFill = color;
}
show() {
fill(this.ballFill);
ellipse(this.pos.x, this.pos.y, this.r * 2);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
}
clicked() {
let d = dist(mouseX, mouseY, this.pos.x, this.pos.y);
if (d <= this.r) {
this.isSelected = true;
} else {
this.isSelected = false;
}
}
}
三注...
請在您的問題中更詳細地說明。 幸運的是,您的代碼不言自明,否則我將不知道您實際上在問什么。 你的帖子描述是“合理的”,但標題有點令人憎惡。
您似乎在繪制橢圓時認為 r 是半徑的一半,因此您將 r 乘以 2。您應該改用ellipseMode(RADIUS)
這樣更清楚這就是您想要的行為。 這使您可以將半徑輸入為圓的寬度的一半,就像您使用r
。 有關更多信息,請參閱此頁面。
您總是勾勒出“下一個”球而不是您單擊的球的輪廓的原因是因為您在更改筆划值之前繪制了球:
這個
show() {
fill(this.ballFill);
ellipse(this.pos.x, this.pos.y, this.r);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
}
應該
show() {
fill(this.ballFill);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
ellipse(this.pos.x, this.pos.y, this.r);
}
您在禁用筆划的情況下繪制選定的球,然后啟用該筆划,然后使用剛剛啟用的筆划繪制下一個未選擇的球,然后再次禁用該筆划。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.