我对 JS 很陌生,所以请原谅我的无知,但如果我在 move() 函数中本地声明我的速度变量,我无法弄清楚为什么我的动画 if 语句不起作用。
如果我不全局声明 speed 变量,女孩会到达 windowWidth 并卡住来回移动几个像素。基本上呆在那里而不是向另一条路移动。
let speed = 2;
class Girl {
constructor(x, y) {
this.x = x,
this.y = y
}
body() {
noStroke();
fill(239, 101, 233);
rect(this.x, this.y, 20, 40);
fill(249, 192, 155);
triangle(this.x, this.y, this.x + 20, this.y, this.x + 10, this.y + 15);
}
move() {
if (this.x > windowWidth + 50 || this.x < -50) {
speed = speed * -1;
}
this.x = this.x + speed;
}
}
我应该提到我正在使用 p5 库,以防我使用任何时髦的函数。它有效,但我确定我可以稍微整理一下。任何建议都将非常受欢迎。
提前致谢!
最佳答案
您不应该在 move
方法中将其声明为局部变量(因为那样会在每次调用时将其重新初始化为 2
),但您应该使其成为在构造函数中初始化并在 move
方法中修改的实例的属性(就像 x
和 y
)。
class Girl {
constructor(x, y) {
this.x = x;
this.y = y;
this.speed = 2;
}
body() {
noStroke();
fill(239, 101, 233);
rect(this.x, this.y, 20, 40);
fill(249, 192, 155);
triangle(this.x, this.y, this.x + 20, this.y, this.x + 10, this.y + 15);
}
move() {
if (this.x > windowWidth + 50 || this.x < -50) {
this.speed = this.speed * -1;
}
this.x = this.x + this.speed;
}
}
关于javascript - 如果我在本地声明我的变量,为什么我的动画不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54816484/