Javascript-使用相同的参数创建多个对象
Javascript - Creating multiple objects with the same parameter
我正在尝试在射击游戏中创建多个"子弹"。
出于某种原因,我只能创建一个,我认为这是因为我没有正确创建多个项目符号对象。
下面是我用来制作拍摄功能的代码。有人能给我指一个正确的方向,告诉我如何一次性重现多个子弹吗?
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>
相关文章:
- 在创建对象后附加一个jquery事件
- 错误:自动化服务器可以't创建对象
- 如何在不使用 new 关键字的情况下从函数创建对象
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 创建对象函数原型和代码是错误的
- 使用Undercore创建对象集合
- 如何在JavaScript中创建对象时使用变量的值
- 正在创建对象的递归列表
- 这两种不同的创建对象文字的方法有什么区别
- ES6 const,用于在JavaScript中创建对象原型;这是一种模式吗
- 使用字符串作为名称创建对象
- 使用参数创建对象
- 如何在JS中创建对象的可变和不可变副本
- 用javascript创建对象的dynamic数组
- Javascript,用vars创建对象的最佳方法
- 离子幻灯片框中未创建对象
- 在创建对象时调用javascript函数
- JavaScript - 有没有办法动态创建对象的新实例
- 为什么使用 Object('123') 创建对象会创建一个 String() 对象,但 typeof 是“对象”
- EmberJS - 在创建对象后添加绑定