JS将原型功能添加到“场景”之外

时间:2018-10-16 14:54:38

标签: javascript object animation prototype game-development

我正在用JS编写一个基本的鼠标精度游戏,并试图将尽可能多的代码移到全局级别,以便可以在多个场景中使用。游戏涉及到移动十字准线(使用鼠标)并单击正方形(其属性和方法由Trgt对象表示),该正方形每帧都会稍微缩小。

Trgt对象存储有关目标的信息(目标的大小,消失的速度)以及目标发生的事情(例如,目标收缩,被击中/点击等)。

See my project on JSFiddle

游戏有4个按此顺序运行的场景:简介->播放->(赢或输)。

我在代码的开头附近为Trgt对象编写了一个构造函数。构造函数是在全局级别而不是在场景内部声明的。

这些方法将被添加到“ Play”场景中的Trgt原型中,但是我想将所有与该原型相关的方法移到播放场景之外的构造函数下,这样看起来更加整洁,从而这些方法可以在后续场景中使用(例如,如果我想添加更多级别)。

当我尝试移动它时,我的代码似乎都没有运行。我遇到黑屏。我在这里做什么错了?

我还想将鼠标单击处理程序从该“播放”场景移到该场景之外(因为我已经成功完成了其他所有场景的鼠标单击处理,包括Play场景之前和之后的场景)

我怀疑我的问题可能与使用“ this”有关,但是我已经玩了一段时间了,而且很沮丧。

播放场景中的方法代码如下:

  Trgt.prototype = {
    shrinkTypeChooser: function() {
      this.shrinkType = Math.floor(Math.random() * 5) + 1; //random integer beween 1 & 5
    },
    shrink: function() {
      this.s -= this.shrinkRate;
      switch (this.shrinkType) {
        case 1: //shrink from top left
          break;
        case 2: //shrink from top right
          this.x += this.shrinkRate;
          break;
        case 3: //shrink from bottom right
          this.x += this.shrinkRate;
          this.y += this.shrinkRate;
          break;
        case 4: //shrink from bottom left
          this.y += this.shrinkRate;
          break;
        case 5: //shrink to centre
          this.x += this.shrinkRate / 2;
          this.y += this.shrinkRate / 2;
          break;
      }
    },

    hit: function() {
      clicks++;
      score++;

      this.reset();
      this.shrinkRate *= this.shrinkMult;
    },
    miss: function() { //called when a click DOES NOT hit a target
      clicks++;
    },
    diss: function() { //called when a target disapears
      disses++;
      this.reset();
    },
    reset: function() { //reset trgt size to base values and chooses a new random position
      trgt.shrinkTypeChooser();
      this.s = Math.floor(Math.random() * this.sUpper) + this.sLower; //random trgt size
      this.x = Math.floor(Math.random() * (canvas.width - this.s));
      this.y = Math.floor(Math.random() * (canvas.height - this.s));
    },
    chooseColor: function() {
      if (hair.x >= trgt.x && hair.x <= (trgt.x + trgt.s) && hair.y >= trgt.y && hair.y <= (trgt.y + trgt.s)) {
        //inside target
        trgt.fillColor = 'red'
      } else {
        //outside target
        trgt.fillColor = 'blue'
      }
    },
    draw: function() {
      this.chooseColor();
      ctx.beginPath();
      ctx.rect(this.x, this.y, this.s, this.s);
      ctx.fillStyle = this.fillColor;
      ctx.fill();
    }
  }

0 个答案:

没有答案