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

3.7k Views Asked by At

Im drawing a circle on html canvas, the circle is meant to indicate a "ship".

I have the current position (x, y) of the "Ship" object and randomly determine a degree (0 to 360) and an amount value. I then want to alter the ship's current position by the degree and amount.

i.E. ship is currently at 100/100 (on a canvas). I determine degree as 30 and amount as 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.

I know it has something to do with Radians, but unfortunally im unable to solve it further.

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

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

There are 2 best solutions below

1
On BEST ANSWER

Yes, all angles in JavaScript are in radians. 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:

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>

1
On

You're right. You have to convert degrees to radians (1 degree = PI/180), then calculate appropriate sine and cosine.

var angle = degrees * Math.PI / 180;
var dx = Math.cos(angle) * amount;
var dy = Math.sin(angle) * amount;
x += dx;
y += dy;