假设我是出于学习目的而制作游戏。
游戏如下:
- 有一个棋盘(这是我的网格:坐标数组)
- 还有一些,我们称它们为在棋盘上随机移动的斑点。
- 移动时,斑点可以复制自己。
我的目标:
是使用循环和setTimeout()逐个移动每个Blob。
为什么要使用setTimeout?
因为我不希望他们同时在棋盘上移动:)
我的问题 :
当blob复制时,新的DOM元素将与Jquery一起注入到网页上。但是,循环已经完成工作,并且由于setTimeout,当循环为每个blob分配新位置时,新的DOM元素就不存在了。
结果 :
只有游戏开始时出现的斑点才在那里获得新的位置。
我的代码示例(简化):
for (var cycles = 1; cycles <= this.cycles + 1; cycles ++)
{
for (var t = 0; t < CHARACTERS_LIST.length; t++) // t => Character Type
{
if (CHARACTERS_LIST[t].length != 0)
{
for (var i = 0; i < CHARACTERS_LIST[t].length; i++) // i => Index
{
// Moves the blob on the chessboard
//
// ***********************************************
MoveCharacter(t, i);
}
}
}
}
//********************************************************************
var loop = 1;
function MoveCharacter(t, i){
CHARACTERS_LIST[x][y].moveAndDupicate(); // Duplicates if Math.ramdon succeeds
LOG.characterHistory(); // Log/Log.js
setTimeout( function(x, y) { return function() {
if (!CHARACTERS_LIST[x][y].isBorn) {
if (x == 0) {
$('#blue-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 1) {
$('#green-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 2) {
$('#red-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
} else if (x == 3) {
$('#special-blob .blob:nth-child(' + (y+1) + ')').css({
'top' : CHARACTERS_LIST[x][y].posY + 'em',
'left' : CHARACTERS_LIST[x][y].posX + 'em'
});
}
} else {
CHARACTERS_LIST[x][y].isBorn = false;
var _blob, _inner;
_blob = document.createElement('div');
_blob.className = "blob";
_inner = document.createElement('div');
_inner.className = "inner";
_blob.appendChild(_inner);
if(CHARACTERS_LIST[x][y] instanceof BlueBlob){
_inner.style = "background-color:#52DE71;";
_blob.style = "top:" + CHARACTERS_LIST[x][y].posY + "em;"
+ "left:" + CHARACTERS_LIST[x][y].posX + "em;";
$('#blue-blob').append(_blob);
} else if (CHARACTERS_LIST[x][y] instanceof GreenBlob){
_inner.style = "background-color:#5299DE;";
_blob.style = "top:" + CHARACTERS_LIST[x][y].posY + "em;"
+ "left:" + CHARACTERS_LIST[x][y].posX + "em;";
$('#green-blob').append(_blob);
}
}
}}(t, i), 100*loop);
loop++;
}
所以...:
- 就像我说的,只有斑点那名最初出现时,比赛开始后,获得了新的岗位。
- 每个周期,CHARACTERS_LIST []被更新。
- 问题似乎在这里:.blob:nth-child('+(y + 1)+')'),因为尚未创建此元素。( 我想... )
我似乎找不到问题,但是我敢肯定,这只是上面代码中的一些小问题!
问题是我试图使用DOM元素和Jquery来实现所有这些功能(效率不高)。我使用了HTML画布,并且一切正常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句