用Javascript创建投射物
我正试图创造和再造太空入侵者。我被困在创造一个从球员的船抛射。射弹(黄色方块)在我不按“A”键的情况下移动用Javascript创建投射物,javascript,p5.js,Javascript,P5.js,我正试图创造和再造太空入侵者。我被困在创造一个从球员的船抛射。射弹(黄色方块)在我不按“A”键的情况下移动 Uncaught TypeError: Cannot set property 'directionY' of undefined at keyTyped (sketch.js:130) at Projectiles.shoot (sketch.js:137) at draw (sketch.js:32) at p5.redraw (p5.js:61731)
Uncaught TypeError: Cannot set property 'directionY' of undefined
at keyTyped (sketch.js:130)
at Projectiles.shoot (sketch.js:137)
at draw (sketch.js:32)
at p5.redraw (p5.js:61731)
at p5.<anonymous> (p5.js:55256)
我打赌这和你如何绑定事件有关,但你没有显示它代码>它会在不按A键的情况下移动,因为你告诉它。然后->
函数keyTyped(){if(key=='a'){this.directionY=-5;
这个
不是你认为的这个
。如果你想访问它,你需要先捕获这个
,或者用这个->keyTyped.call(这个)
class Projectiles {
constructor(color, positionX, positionY, sizeWidth = 50, sizeHeight = 25) {
this.color = color;
this.positionX = positionX;
this.positionY = positionY;
this.sizeWidth = sizeWidth;
this.sizeHeight = sizeHeight;
// default speed
this.directionY = -5;
}
// create ship with default properties
createShip() {
fill(this.color);
rect(this.positionX, this.positionY, this.sizeWidth, this.sizeHeight);
}
shoot() {
this.positionY = this.positionY + this.directionY;
//
function keyTyped() {
if (key === 'a') {
this.directionY = -5;
} else if (key === 'b') {
this.directionY = 5;
}
// uncomment to prevent any default behavior
// return false;
}
keyTyped();
}
}