我正在尝试在 html 5 Canvas 中制作一个“贪吃蛇”游戏。但是我在让蛇向正确的方向移动时遇到了问题。我假设以下代码会使蛇水平移动 0 度和 180 度,垂直移动 90 度和 270 度,但事实并非如此。我在这里做错了什么? (使用向左和向右箭头进行导航)。
function move(direction) {
if(direction == left) {
angel = (angel - 5) % 360;
if(angel < 0) angel += 360;
} else if (direction == right) {
angel = (angel + 5) % 360;
}
x = x + Math.floor(Math.cos(angel*0.0174532925)*5);
y = y + Math.floor(Math.sin(angel*0.0174532925)*5);
$("#infoBar").html("Direction: " + direction + " angel: " + angel);
drawPoint(x,y);
}
乘数当然是辐射度数。但不知何故,270 度并不是一条垂直直线,正如我所假设的那样。我做错了什么?
最佳答案
因为 float 学。
余弦(270 度)= 0
Buuuut:
Math.cos((Math.PI/180)*270)
不是 0
。它是:-1.836909530733566e-16
换句话说,它是 -0.000000000000000183 等。非常接近于零,但略小于零!
但是您正在使用 Math.floor
,并且 Math.floor
那个数字(或者 Math.floor(-0.1)
物质)= -1。
你不想要那个。
使用 Math.round
而不是 Math.floor
。
这是为您修复的实例:http://jsfiddle.net/UtPJz/3/
关于html - html5 Canvas 中的 "snake"。数学曲线问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8478328/