我正在制作一个具有移动形状的简单画布游戏。当我在循环中更新飞船的位置时,它仅适用于几帧,然后该对象变为未定义,该对象的x,y属性变为NaN,并且速度变为类似1.137658463e-16
我几乎肯定这是更新功能的问题,但我不确定这是什么问题。我让控制台在迭代中打印对象,这是
之前和之后的一些代码片段//before
x: 300,
y: 296,
angle: 0,
velocity: 0.40000000000000013,
update: [Function],
isThrusting: false,
maxVelocity: 8,
//after
x: NaN,
y: NaN,
angle: NaN,
velocity: -0.3999999999999999,
update: [Function],
isThrusting: false,
maxVelocity: 8,
//Code
var gameState = {
ships: {}
}
var Entity = function(x,y,angle){
var self = {
x:x,
y:y,
angle:angle,
velocity:2
}
self.update = function(){
self.x += self.velocity * Math.sin(self.angle);
self.y -= self.velocity * Math.cos(self.angle);
}
return self;
}
var Ship = function(x,y,angle){
var self = Entity(x,y,angle);
self.isThrusting = false;
self.maxVelocity = 8;
self.bullets = {};
self.update = function(){
if(self.isThrusting){
self.velocity += 1;
self.x += self.velocity * Math.sin(self.angle);
self.y -= self.velocity * Math.cos(self.angle);
if(self.velocity >= self.maxVelocity){
self.velocity = self.maxVelocity;
}
}else {
if(self.velocity > 0){
self.velocity -= 0.4;
self.x += self.velocity * Math.sin(self.angle);
self.y -= self.velocity * Math.cos(self.angle);
}
}
}
return self;
}
//here I initialize the object
io.sockets.on('connection', function(socket){
gameState.ships[socket.id] = new Ship(300,300, 0);
});
//here is the loop of the update
setInterval(function(){
for(var i in gameState.ships);
var ship = gameState.ships[i];
ship.update();
}
}, 1000/60);
答案 0 :(得分:1)
我正在根据光标在画布上的位置计算船的角度。当我开始游戏并且鼠标仅在画布外时会发生此问题,这会发送一个空变量导致此问题...我通过设置光标位置的默认值直到光标接触画布来解决了该问题。>