只是想在我的游戏中实现碰撞。
我对如何测试图 block 的碰撞有疑问,因此碰撞不起作用。
我有一个如下所示的数组:
var coll_array = [
[[tile_index],[x],[y]]
]
图 block 索引是我使用的图像映射中图 block 的编号,x是图 block 的x位置,y是图 block 的y位置。
基本上,如果tile_index不为0,那么玩家应该碰撞到这个图 block ,这就是我想要实现的目标。
请参阅代码示例的更新
出于某种原因,变量碰撞不断返回 false,尽管我不确定为什么,但我相信这与我设置数组的方式有关。
任何帮助将不胜感激。我有游戏的真人版here
用户名=访客
密码=访客。
请使用新游戏,以便您可以看到正确的console.log
我已将数组的控制台日志放入播放器函数中,以便您可以查看其设置方式。
谢谢
更新
好的,经过一番尝试后,代码现在看起来像这样:
function Player()
{
var sprite = new Sprite(),
collision_array,
collided,
x,
y,
w = sprite.width,
h = sprite.height,
gameW = canvas.width,
gameH = canvas.height-192,
block_x,
block_y,
block_cx,
block_cy,
combined_hw = 32,
combined_hh = 32,
player_cx,
player_cy;
this.keys = [];
// What delay do we want to use between switching sprites (in milliseconds)
this.moveSpeed = 4;
this.player = null;
this.init = function(coll_data){
collision_array = coll_data;
console.log(collision_array);
};
this.init_Player = function(pos_X, pos_Y){
this.player = sprite.load("player");
x = pos_X;
y = pos_Y;
};
this.update = function(elapsed) {
// perform a switch statement on the last key pushed into the array
// this allows us to always move the direction of the most recently pressed
// key
switch (this.keys[this.keys.length - 1])
{
case 37:
// move the player left on the screen
x -= this.moveSpeed * elapsed;
break;
case 38:
// move the player up on the screen
y -= this.moveSpeed * elapsed;
break;
case 39:
// move the player right on the screen
x += this.moveSpeed * elapsed;
break;
case 40:
// move the player down on the screen
y += this.moveSpeed * elapsed;
break;
}
if (x < 0)
{
x = 0;
}
if (x >= gameW - w)
{
x = gameW - w;
}
if (y < 0)
{
y = 0;
}
if (y >= gameH - h)
{
y = gameH - h;
}
player_cx = x+(32/2);
player_cy = y+(32/2);
collision_array.forEach(function(row) {
for(var i = 0; i<row.length;i++){
if(row[i][0] != 0){
block_x = row[i][1];
block_y = row[i][2];
block_cx = block_x+(32/2);
block_cy = block_y+(32/2);
}
}
collided = Math.abs(player_cx - block_cx)< combined_hw
&& Math.abs(player_cy - block_cy)< combined_hh;
});
if(collided)
{
console.log("COLLIDED!")
}
return {
'pos_X':x,
'pos_Y':y
};
};
this.draw = function() {
ctx.drawImage(this.player,x, y, w ,h);
};
}
这可行,但仅适用于数组中存储的最后一个位置,例如右下角,你们能看到我哪里错了吗?
最佳答案
我只是很快地读完这篇文章,但你说它只适用于最后一个 block ,也许你应该尝试一下。
collided |= Math.abs(player_cx - block_cx)< combined_hw
&& Math.abs(player_cy - block_cy)< combined_hh;
ORing 发生碰撞,因此如果任何 block 发生碰撞,则结果为 true。
关于javascript - 碰撞数组无法正常工作javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16004197/