javascript - 为什么我的水箱无法正常旋转?

标签 javascript html canvas rotation

我有一辆移动坦克:http://www.exeneva.com/html5/movingTankExample/

坦克使用有限状态机来确定其面向的方向,默认设置为“向上”:

var tankDir = "up";

处理旋转的函数如下:

function dirTank(dir) {
  switch (dir) {
    case "up":
      if (tankDir == "right") {
        rotationAngle += -90;
      } else if (tankDir == "down") {
        rotationAngle += 180;
      } else if (tankDir == "left") {
        rotationAngle += 90;
      }
      break;
    case "down":
      if (tankDir == "up") {
        rotationAngle += 180; 
      } else if (tankDir == "right") {
        rotationAngle += 90;
      } else if (tankDir == "left") {
        rotationAngle += -90;
      }
      break;
    case "left":
      if (tankDir == "up") {
        rotationAngle += -90;
      } else if (tankDir == "right") {
        rotationAngle += 180;
      } else if (tankDir == "down") {
        rotationAngle += 90;
      }
      break;
    case "right":
      if (tankDir == "up") {
        rotationAngle += 90;
      } else if (tankDir == "down") {
        rotationAngle += -90;
      } else if (tankDir == "left") {
        rotationAngle += 180;
      }
      break;
  }
  tankDir = dir;
  rotationAngle %= 360;
}

drawScreen中的坦克渲染代码如下所示:

  // Draw the tank
  context.save();
  context.setTransform(1,0,0,1,0,0); // identity matrix
  context.translate(tankX + tileWidth/2, tankY + tileHeight/2);
  rotationAngle = rotationAngle * Math.PI/180;
  context.rotate(rotationAngle);
  context.drawImage(tileSheet, tankSourceX, tankSourceY, tileWidth, tileHeight, -tileWidth/2, -tileHeight/2, tileWidth, tileHeight);
  context.restore();

但是坦克似乎转动了,然后突然又回到了原来的方向。有人可以帮我解决这个问题吗?

最佳答案

rotationAngle 应保留在另一个变量中,并且所有分配都应更改为增加或减少当前 Angular ,例如

rotationAngle += 90; // turn right
rotationAngle += 180; // reverse direction

完成这些更改后,您需要标准化 Angular :

rotationAngle %= 360;

更新

Make sure to not overwrite the `rotationAngle` later in the code when you convert from degrees to radians.

rotationAngle = rotationAngle * Math.PI/180;

应该变成:

rotationAngleRad = rotationAngle * Math.PI/180;

然后在 .rotate() 调用中使用 rotationAngleRad

关于javascript - 为什么我的水箱无法正常旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670864/

相关文章:

javascript - GWT 包括模块 list 中的外部 javascript 文件

javascript - AWS Lambda w/Google Vision API 抛出 PEM_read_bio:no start line 或 Errno::ENAMETOOLONG

python - 使用python从网站中提取img url

javascript - Position Fixed - 设置宽度等于容器

JavaFX 裁剪产生 'lottery scratch ticket' -Effect

javascript - 如何使用 JavaScript 弹出 jQuery 移动选择?

html - 如何让高度真正达到100%

html - 为什么我的 HTML5 矩形看起来放大了?

javascript - 在 vue.js 应用程序中使用外部 js 库

javascript - 在一页上渲染多个 CanvasJS 图表时出现问题