【问题标题】:Why won't my tank rotate properly?为什么我的水箱不能正常旋转?
【发布时间】:2012-05-20 13:37:25
【问题描述】:

我有一个移动坦克: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();

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

【问题讨论】:

  • 看起来问题并不在于那段代码。
  • 你的坦克有点失控
  • 格鲁伯中尉会很高兴知道他的小坦克现在可以旋转了 :)

标签: javascript html canvas rotation


【解决方案1】:

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

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

在这些更改之后,您需要对角度进行归一化:

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

【讨论】:

  • 已更新,但仍未完全正常运行。
  • @YangPulse 这是什么意思?你在看什么?
  • 我根据你的 cmets 更新了代码,但我看到的和我看到的一样。
  • @YangPulse 如果您更新了代码,请更新问题以便所有人都能看到。谢谢
  • 完成。抱歉,我是 StackOverflow 的新手。
【解决方案2】:

原因是每次重绘画布时都需要更改旋转,而不仅仅是第一次。

【讨论】:

  • @YangPulse 在超时期间调用的 drawScreen 函数期间怎么样?
  • 啊,就是这样。知道如何解决吗?
  • 将旋转保存为全局变量,然后将代码添加到drawScreen中以相应地绘制坦克。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多