sty*_*yke 4 javascript arrays html5 canvas
我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
现在,在渲染之前,它们也会通过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 (){
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在www.techgoldmine.com找到源代码,并且我可以找到最远的源代码
您的代码中存在错误,请参阅此处的注释:
function updateTurbines(){
tempTurbine = {}
turbinePositionTop = tempTurbine.y; // tempTurbine is an empty object right now so .y is undefined
turbinePositionBottom = tempTurbine.y + tempTurbine.height; // same problem here
for (var i = turbineArrayLength; i < 2; i++){ // why am I starting at the end of the array? What's the 2 for?
tempTurbine = turbines[i];
for (var i = turbineArrayLength; i < 2; i++){ // why am I doing this twice? I'm also clobbering the value of "i"
if (tempTurbine !== tempTurbines[i]){
while (){
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在不知道它在做什么的情况下重写的方法:
function updateTurbines(){
var l = turbines[i].length; // get the turbine length directly from the array[1]
for (var i = 0; i < l; i++){ // go through all of the turbines
var tempTurbine = turbines[i];
turbinePositionTop = tempTurbine.y; // now .y is defined because tempTurbine is not an empty object
turbinePositionBottom = tempTurbine.y + tempTurbine.height;
for (var j = 0; j < l; j++) { // NOT i but j here
if (tempTurbine !== tempTurbines[j]){
while (){
// ...
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
[1]如果修改数组,这可能会导致错误.我假设你现在只添加它.