我是JS的新手,所以请原谅我的无知,但是如果我在move()函数中本地声明我的速度变量,我无法弄清楚为什么我的动画if语句不起作用。
如果我没有全局声明速度变量,那么女孩会进入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;
}
}
因为speed
的值在多次调用move
时共享。如果你在move
中声明它,那么每次调用move
都会创建它,因此任何先前的speed
值都将被忽略。
如果你不希望speed
成为全局变量,那么你可以使它成为类Girl
的属性:
class Girl {
constructor(x, y) {
this.x = x;
this.y = y;
this.speed = 2; // make 'speed' a property of the class
}
/* ... */
// use 'this.speed' inside 'move' instead of just 'speed'
move() {
if (this.x > windowWidth + 50 || this.x < -50) {
this.speed = this.speed * -1;
}
this.x = this.x + this.speed;
}
}
这里的问题是this.x > windowWidth + 50 || this.x < -50
。尝试在this
函数中记录move()
,你会发现它指的是move().x
而不是Girl.x
。所以this.x
是undefined
,而undefined > 10 + 50
总是假的。
附:我不知道p5所以这是香草。
所以要解决这个问题,你需要声明另一个变量来获得Girl
范围。
var Girl = function(){
var self = this;
//code goes here
function move(){
self.x = setValue;
console.log(this.x) //undefined
}
}