我正在创建一个Snake游戏(就像旧手机上的游戏一样)。我在下面有一段代码,它似乎显示了一个对象在各行之间改变其值的怪异行为。Javascript对象更改行间值
函数makeSnakeArray
在游戏开始时或当蛇自身触及(游戏重新开始)时被调用。它返回一个新的蛇,它是一个x
和y
属性的对象数组,存储在全局变量snakeArray
中。
第一次被调用时,一切正常。但是,当它被称为重新启动游戏时,x
和y
值在consoleLog1
和consoleLog2
(请参阅代码注释)中有所不同。
在consoleLog1
中,x
和y
的值与我在函数中计算的一样。但是,在consoleLog2
中,tempArray
会打印出snakeArray
在要求重新启动游戏时的情况(并且在调用makeSnakeArray
函数之前,我确定通过设置snakeArray = [];
来清除snakeArray
)。结果,蛇不像第一次那样在屏幕中间开始,但它似乎继续在它离开的地方。
为什么会发生这种情况?
功能:
function makeSnakeArray(){
var tempArray = [];
//Get the position of the head of the snake
var halfWidth = Math.floor(canvasWidth/2) * blockSize;
var halfHeight = Math.floor(canvasHeight/2) * blockSize;
//Add in each block of the snake to the snake array, starting with the head
for (var i = 0; i < startingSnakeLength; i++){
//Create and initialize the snakeBlock
var snakeBlock = {
x: halfWidth,
y: halfHeight + (i*blockSize),
}
console.log(snakeBlock); //consoleLog1
tempArray.push(snakeBlock);
}
console.log(tempArray);//consoleLog2
return tempArray;
}
输出示例:
consoleLog1
{x: 180, y: 180}
{x: 180, y: 195}
{x: 180, y: 210}
{x: 180, y: 225}
{x: 180, y: 240}
consoleLog2
0:{x: 60, y: 270}
1:{x: 60, y: 285}
2:{x: 60, y: 300}
3:{x: 60, y: 315}
4:{x: 60, y: 330}
这里是当前VERSI如果你想看到完整的代码:https://codepen.io/vrsivananda/pen/NvJyGJ?editors=0010
这似乎是全球位置不正确复位,蛇似乎继续在那里。 –
你是什么意思,我该如何重置全球职位? –
对不起,我的意思是你的全球蛇阵列 –