1

我在 html 画布上画了一个圆圈,这个圆圈表示“船”。

我有“Ship”对象的当前位置(x,y)并随机确定度数(0 到 360)和数量值。然后我想通过程度和数量来改变船的当前位置。

iE 船目前为 100/100(在画布上)。我将学位确定为 30,数量确定为 50。

现在我想基于以下假设获得船舶的新位置:0 度表示“笔直向上”,180 度表示笔直向下,而 50 度表示向确定的方向移动 50 个像素。

我知道它与弧度有关,但不幸的是我无法进一步解决它。

var ship = {
  x: 100,
  y: 100
}

var movement = {
  degrees: 30,
  amount: 50
}
4

2 回答 2

4

是的,JavaScript 中的所有角度都是弧度。此外,画布上下文向右有 0° 点,因此如果您希望 0° 直上,则需要从所有角度减去 90°:

var angle = (movement.degrees - 90) / 180 * Math.PI;  // compensate angle -90°, conv. to rad
ship.x += movement.amount * Math.cos(angle);          // move ship
ship.y += movement.amount * Math.sin(angle);

var movement = {
  degrees: 30,
  amount: 50
}

var ctx = document.querySelector("canvas").getContext("2d");

(function loop() {
  ctx.clearRect(0, 0, 300, 150);

  var ship = {  // reset ship position for demo
    x: 100,
    y: 90
  }

  ctx.strokeRect(ship.x - 2, ship.y - 2, 4, 4);
  ctx.fillText("From", ship.x + 5, ship.y);

  var angle = (movement.degrees - 90) / 180 * Math.PI; // compensate angle -90°, conv. to rad
  ship.x += movement.amount * Math.cos(angle); // move ship
  ship.y += movement.amount * Math.sin(angle);

  ctx.strokeRect(ship.x - 2, ship.y - 2, 4, 4);
  ctx.fillText(movement.degrees + "°", ship.x + 5, ship.y);
  
  movement.degrees++;
  movement.degrees = movement.degrees % 360;
  requestAnimationFrame(loop);
})();
<canvas></canvas>

于 2015-06-18T10:19:30.947 回答
1

你是对的。您必须将度数转换为弧度 ( 1 degree = PI/180),然后计算适当的正弦和余弦。

var angle = degrees * Math.PI / 180;
var dx = Math.cos(angle) * amount;
var dy = Math.sin(angle) * amount;
x += dx;
y += dy;
于 2015-06-18T09:47:32.640 回答