简体   繁体   English

如何将度数值更改为实际的x / y位置变化?

[英]How to alter a degree value into an actual x/y position change?

Im drawing a circle on html canvas, the circle is meant to indicate a "ship". 我在html画布上绘制一个圆圈,圆圈表示“船”。

I have the current position (x, y) of the "Ship" object and randomly determine a degree (0 to 360) and an amount value. 我有“Ship”对象的当前位置(x,y)并随机确定度数(0到360)和金额值。 I then want to alter the ship's current position by the degree and amount. 然后我想根据程度和数量改变船的当前位置。

iE ship is currently at 100/100 (on a canvas). iE船目前为100/100(在画布上)。 I determine degree as 30 and amount as 50. 我确定度数为30,数量为50。

Now i would like to get the ships new location based on the assumption that 0 degree would indicate "straight up" and 180 degree would indicate straight down while 50 amount indicate a movement of 50 Pixels into the direction determined. 现在我想基于0度将指示“直线向上”并且180度将指示直线向下而50度量指示50个像素移动到所确定的方向的假设来获得船舶新位置。

I know it has something to do with Radians, but unfortunally im unable to solve it further. 我知道它与Radians有关,但遗憾的是我无法进一步解决它。

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

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

Yes, all angles in JavaScript are in radians. 是的,JavaScript中的所有角度都是弧度。 In addition, the canvas context has 0° point to the right so you need to subtract 90° from all angles if you want 0° to be straight up: 此外,画布上下文向右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> 

You're right. 你是对的。 You have to convert degrees to radians ( 1 degree = PI/180 ), then calculate appropriate sine and cosine. 您必须将度数转换为弧度( 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM