检查数组中的变量
checking variable within array
第一次在这里发帖,第一次用Javascript创建游戏。
我正在尝试在游戏中的两个对象(子弹和敌人(之间创建碰撞,但现在,只是尝试仅用子弹到达屏幕顶部时发生一些事情。
当我按 E 时,会发生这种情况:
if (69 in keysDown && timer == 0) //E
{
var newbullet = Object.create(bullet);
newbullet.posx = ship.playerx;
newbullet.posy = ship.playery;
projectiles.push(newbullet);
ship.shoot = true;
}
然后,项目符号向上移动,如其更新功能中所述。
我在我的游戏循环中不断运行这个函数,它检查冲突,看起来像这样:
function Collision()
{
for (i = 0; i <= projectiles.length; i++)
{
if (bullet.posy < 0 )
{
ctx.fillText("HIT" , 160, 340);
ship.health -= 1;
}
}
}
但它不起作用。我想用"projectiles[i].posy"代替"bullet.posy",但最终说projectiles[i]是未定义的。
射弹是一个全局阵列。
var projectiles=[];
这是项目符号:
var bullet =
{
posx:0,
posy:0,
speed: 10,
power: 2,
draw: function()
{
ctx.fillStyle = "rgb(200,100,0)";
ctx.beginPath();
ctx.rect(((this.posx - 5)), (this.posy - 30), 10, 25);
ctx.closePath();
ctx.fill();
},
setup: function(ax, ay)
{
this.posx = ax;
this.posy = ay;
},
update: function()
{
this.posy -= this.speed;
}
};
有什么帮助或建议吗?
这是链接,如果你想尝试一下E 拍摄。
谢谢。
第一部分似乎很清楚:调用一个名为 newbullet
的新项目符号对象,键的值由 ship.playerx
和 ship.playery
设置.posx
和.posy
。 然后将newbullet
存储在projectiles
数组中。
其余的就不太清楚了。正如你所看到的,Collision()
中 for 循环的 if 条件似乎引用了new bullet()
构造函数的.posy
,而不是刚刚创建的对象的.posy
(newbullet
(。 您还需要迭代 for 循环projectiles.length - 1
次,因为数组是零索引的:因此请使用 <
运算符,而不是 for 循环中的<=
运算符。
假设ship.playery
分配了一个数字值,也许尝试在"射弹"数组通过 Collision()
的 for 循环时为它中的每个项目分配一个变量......
function Collision() {
var projLength = projectiles.length; // slight optimisation to for-loop
for (i = 0; i < projLength; i++) {
var thisBullet = projectiles[i]; // reassign variable each iteration
if (thisBullet.posy < 0 ) {
ctx.fillText("HIT" , 160, 340);
ship.health -= 1;
}
}
}
编辑:根据更新的问题
由于您拥有用于存储子弹的projectiles
数组,您可以轻松地将bullet
文字对象转换为构造器,并根据需要/允许任意数量进行构建。然后,您的代码将遵循我第一段中的描述,看起来像......
var projectiles = [];
var Bullet = function(x, y) {
this.posx: x,
this posy: y,
speed: 10,
power: 2,
draw: function() {
ctx.fillStyle = "rgb(200,100,0)";
ctx.beginPath();
ctx.rect(((this.posx - 5)), (this.posy - 30), 10, 25);
ctx.closePath();
ctx.fill();
},
setup: function(ax, ay) {
this.posx = ax;
this.posy = ay;
},
update: function() {
this.posy -= this.speed;
}
};
/* --- */
if (69 in keysDown && timer == 0) { // E
var bullet = new Bullet(ship.playerx, ship.playery);
projectiles.push(bullet);
ship.shoot = true;
}
/* --- */
function Collision() {
// as above ....
}
。这也意味着您不必等待子弹到达y < 0
就可以创建另一个子弹。 速射耶!!
- Angularjs:访问范围变量数组并计算平均值
- 将 php 变量(数组)json_encode JavaScript 变量时的键排序
- 具有公共属性的变量数组
- Highcharts将变量数组添加到序列中
- 如何在Javascript函数中添加php变量/数组(在jsGrid({controller})中)
- Javascript项目通过变量数组进行搜索
- 用于交替结果的变量数组
- 如何将变量数组从 laravel 控制器传递到我的 ajax 函数
- 如何在 Javascript 中从数组创建变量数组
- 使用 Javascript 创建变量数组(动态,下拉)
- .serialize() Javascript 中的变量数组
- 更改全局变量(数组)的 JavaScript 函数
- 使用变量数组调用函数
- 使用 JavaScript 变量数组
- 如何使用静态变量数组
- 变量数组+正则表达式不能一起工作
- 将变量数组大写
- 变量数组中的对象是否可能有2个值
- 将java变量/数组传递给android webview中的javascript
- 从for循环(Javascript)中创建变量数组