html - html5 Canvas 中的 "snake"。数学曲线问题

标签 html canvas curve

Demo

我正在尝试在 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 度并不是一条垂直直线,正如我所假设的那样。我做错了什么?

Javascript file.

Html file.

最佳答案

因为 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/

相关文章:

javascript - 如何使用 javascript 或 html 下载 PDF 格式的填写表格

javascript - 在javascript中将base64转换为blob

ios - 使用 ObjectiveC 的 Core Graphics,如何将箭头绕圆圈弯曲?

python - 将开放曲线转换为有序像素列表 : a Python test code with numpy

html - Firefox 按钮 CSS 问题

html - 将页脚图像与内容区域对齐

javascript - 我想将该按钮链接到另一个页面

javascript - 在 HTML5 中堆叠多个 Canvas

javascript - HTML5 Canvas : How to draw a constant-sized image that translates properly when zooming?

gnuplot - 将 acspline 与 fillcurve 数据结合起来