Search code examples
htmlcanvascurve

"snake" in html5 canvas. Math curve issue


Demo

I am trying to make a "snake" game in html 5 canvas. But i have a problem getting the snake to move the right direction. I would assume that the following code would make the snake move horizontal on 0 and 180 degrees, and vertical on 90 and 270 degrees, this is however not the case. What am i doing wrong here? (Use the left and right arrows to navigate).

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);
}

The multiplier is of course degrees to radiant. But somehow 270 degrees is not a straight vertical line, as i would assumed that it was. What am i doing wrong?

Javascript file.

Html file.


Solution

  • Because of floating point math.

    cos(270 degrees) = 0

    Buuuut:

    Math.cos((Math.PI/180)*270) is not 0. It is: -1.836909530733566e-16

    In other words it is -0.000000000000000183, etc. Very close to zero, but slightly less than zero!

    But you're using Math.floor, and Math.floor that number (or Math.floor(-0.1) for that matter) = -1.

    You don't want that.

    Use Math.round instead of Math.floor.

    Here's a live example of it fixed for you: http://jsfiddle.net/UtPJz/3/