html5画布中的"蛇".数学曲线问题

ran*_*oms 2 html curve canvas

演示

我想在html 5画布中制作一个"蛇"游戏.但我有一个问题让蛇向正确的方向移动.我假设下面的代码会使蛇在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);
}
Run Code Online (Sandbox Code Playgroud)

乘数当然是辐射度.但不知何故,270度并不是一条直线,正如我所想的那样.我究竟做错了什么?

Javascript文件.

Html文件.

Sim*_*ris 6

因为浮点数学.

cos(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/