【发布时间】:2012-02-29 06:28:12
【问题描述】:
我正在使用 HTML5 的 canvas API 用 Javascript 制作游戏,但遇到了障碍。
其中一个游戏效果是导弹沿 y 轴向上飞行,它受到沿 x 轴移动的阵风(由涡轮机发出)的影响。我制造其中一台涡轮机没有问题,但是当它们的数量增加到 3 台时,我遇到了麻烦。 在一个新的层次上,我将这些涡轮机实例化为对象,然后将其推入一个数组中,如下所示:
function gameStateNewLevel(){
for (var i = 0; i < 2; i++){
turbine = {};
turbine.width = 10;
turbine.height = Math.floor(Math.random()*200); //turbine height
turbine.y = Math.floor(Math.random()*600) //turbine y-axis
if (Math.random()*10 > 5){ //indicates turbine side of canvas
turbine.side = leftSide;
}else{
turbine.side = rightSide;
}
if(turbine.height <= 100){ //Increases turb. size if it's too small
turbine.height += Math.floor(Math.random()*100);
}
turbines.push(turbine);
}
context.fillStyle = "#FFFFFF"
switchGameState(GAME_STATE_PLAYER_START);
}
现在,在渲染它们之前,它们也会通过 updateTurbine 函数进行更新。所有这个函数应该做的是确保涡轮机没有相互重叠,并根据需要将它们向上或向下移动 y 轴(通过循环遍历数组并比较其中的每个对象)。我已经尝试过制作这个功能,但我完全迷失在所有循环之间。就我所知,这差不多,我感觉我走错了路:
function updateTurbines(){
tempTurbine = {}
turbinePositionTop = tempTurbine.y;
turbinePositionBottom = tempTurbine.y + tempTurbine.height;
for (var i = turbineArrayLength; i < 2; i++){
tempTurbine = turbines[i];
for (var i = turbineArrayLength; i < 2; i++){
if (tempTurbine !== tempTurbines[i]){
while (){
}
}
}
}
}
你可以在 www.techgoldmine.com 找到源代码和我得到的最远的东西而不破坏这个东西
【问题讨论】:
-
建议:您的
if(turbine.height <= 100){应该是while(turbine.height <= 100){,以防新号码仍低于 100。 -
@Jeffrey 或者从一开始就使用
100 + Math.random()*100... -
@Andrew 是的...这可能是一个更好的主意 :)
标签: javascript arrays html canvas