Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate a point to specified distance at a specified angle? [closed]

I want to translate a point to specific distance, along a line whose angle is given in degrees.

var initialPoint = [0,0];   //Starting Point
var distance = 100;         //Distance in pixels to be translated
var degree = 45;            //Direction of move
var translatedPoint = moveByDegree(initialPoint, degree, distance);

function moveByDegree(initialPoint, degree, distance)
{
    //formula to generate translatedPoint by degree & distance
    // . . . 

    return translatedPoint;
}
  • 0 degree should move UP.
  • 180 degree should move DOWN.
  • 90 degree should move RIGHT.
  • 270 degree should move LEFT.
  • Other angles would correspond to a DIAGONAL direction.

Give me simple algorithm or JavaScript code.

like image 651
Rashid Avatar asked Dec 24 '22 22:12

Rashid


1 Answers

You have to give the initial point, the angle and the unit of movement.

Math.radians = function(degrees) {
  return degrees * Math.PI / 180;
};

function move(point, angle, unit) {
  var x = point[0];
  var y = point[1];
  var rad = Math.radians(angle % 360);

  x += unit*Math.sin(rad);
  y += unit*Math.cos(rad);

  return [x, y];
}

move([0,0], 180, 100);  // [0, 100]
like image 66
Ali Yousuf Avatar answered Dec 26 '22 11:12

Ali Yousuf