Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Javascript创建投射物_Javascript_P5.js - Fatal编程技术网

用Javascript创建投射物

用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)

我正试图创造和再造太空入侵者。我被困在创造一个从球员的船抛射。射弹(黄色方块)在我不按“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)
    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();

  }
}