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

Javascript - Creating multiple objects with the same parameter

本文关键字:创建 对象 参数 Javascript-      更新时间:2023-09-26

我正在尝试在射击游戏中创建多个"子弹"。

出于某种原因,我只能创建一个,我认为这是因为我没有正确创建多个项目符号对象。

下面是我用来制作拍摄功能的代码。有人能给我指一个正确的方向,告诉我如何一次性重现多个子弹吗?

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();
}

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

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

您想要使用原型模式:

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();

在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>