Javascript - 使用相同的参数创建多个对象

时间:2015-12-31 13:47:37

标签: javascript object canvas onclick draw

我试图创造多个"子弹"在射击游戏中。

出于某种原因,我只能创建一个,我认为它是因为我没有正确创建多个子弹对象。

以下是我用于制作拍摄功能的代码。有人可以指出我如何在onclick上重建多个子弹吗?

bullet = {

    x: null,
    y: null,
    width: 10,
    height: 10,
    direction: null,

    update: function(){

        if(this.direction == null){
            if(lastKeyPress == null){
                lastKeyPress = up;
            }
            this.direction = lastKeyPress;
        }
        if(this.direction == up){ this.y -=7; }
        if(this.direction == down){ this.y +=7; }
        if(this.direction == left){ this.x -=7; }
        if(this.direction == right){ this.x +=7; }
    },
    draw: function() {
        if(this.x == null){
            this.x = player.x + (player.width/4);
        }
        if(this.y == null){
            this.y = player.y + (player.height/4);
        }
        cContext.fillRect(this.x, this.y, this.width, this.height);
    }
}

function main(){
    canvas = document.getElementById("mainCanvas");
    cContext = canvas.getContext("2d");

    keystate = {};
    document.addEventListener("keydown", function(evt) {
        keystate[evt.keyCode] = true;
    });
    document.addEventListener("keyup", function(evt) {
        delete keystate[evt.keyCode];
    });
    document.addEventListener("click", function(evt) {
        bullets[bulletNum] = bullet;
        bullets[bulletNum].draw();
        bulletNum++;
    });

    init();

    var loop = function(){
        update();
        draw();

        window.requestAnimationFrame(loop, canvas);
    }
    window.requestAnimationFrame(loop, canvas);
}

function update() {
    for (i = 0; i < bullets.length; i++) { 
        bullets[i].update();
    }
    player.update();
    ai.update();
}

function draw() {
    cContext.clearRect(0, 0, WIDTH, HEIGHT);

    cContext.save();

    for (i = 0; i < bullets.length; i++) { 
        bullets[i].draw();
    }
    player.draw();
    ai.draw();

    cContext.restore();
}

问题在于,一旦你射出一颗子弹就不能再射击了。

我知道这里有很多代码,任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

您想使用原型模式:

var Bullet = function() {
    this.x = null;
    this.y = null;
    this.width = 10;
    this.height = 10;
    this.direction = null;
};
Bullet.prototype.update = function() {...};
Bullet.prototype.draw = function() {...};

var bullet = new Bullet();

答案 1 :(得分:0)

在javascript中定义对象的另一种方法是使用原型,例如:

function Person(name){
   this.name = name; 
}

Person.prototype.sayHello = function(){
   var res = "Hello i am "+ this.name;  
  return res;
}

var jhon = new Person('Jhon');
var rose = new Person('Rose');

document.getElementById('jhon').innerHTML = jhon.sayHello();
document.getElementById('rose').innerHTML = rose.sayHello();
<html>
  <head>
    <title>
      </title>
    </head>
  <body>
    
    <h1 id="jhon"></h1>
    
    <h1 id="rose" ></h1>
    </body>
  
  </html>