如何将一个点以指定的角度平移到指定的距离? [关闭]

问题描述 投票:0回答:1

我想沿着一条角度以度为单位的线将一个点平移到特定距离。

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度应该向上移动。
  • 180 度应向下移动。
  • 90 度应向右移动。
  • 270 度应向左移动。
  • 其他角度对应于对角线方向。

给我简单的算法或JavaScript代码。

javascript math geometry trigonometry
1个回答
13
投票

你必须给出初始点,角度和移动单位。

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

function move(point, angle, unit) {
  const rad = Math.radians(angle % 360);

  let [x, y] = point;
  x += unit * Math.sin(rad);
  y -= unit * Math.cos(rad);

  return [x, y];
}

//////////////////
// demo:
const FPS = 60;
const jump = 3;
let angle = 135;
let point = [0, 0];

function animate () {
  // calculate new point
  point = move(point, angle, jump); 
  const [x, y] = point;
  
  // update ball position
  ball.style.left = x + 'px'
  ball.style.top = y + 'px'

  // continue animating while conditions fulfils
  if( x >= 100 && y >= 100 )
    angle = -45;
  else if( x <= 0 && y <= 0 )
    angle = 135;

  setTimeout(animate, 1000/FPS);
}

animate();
b {
  padding: 10px;
  background: red;
  position: absolute;
  border-radius: 50%;
}
<b id='ball'></b>

输出看起来像

[1.2246467991473532e-14, 100]
- 这是由于浮点单元 (FPU) 算法的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.