根据距离和方向计算坐标

时间:2019-04-17 08:20:02

标签: javascript

这是我方便的方案:

enter image description here

给出:

  • 这是2D,无需担心第三轴
  • ABAB都具有xy坐标
  • width,到每个角的距离:width / 2
  • direction的度数(0向上,90右,180向下等)

如何计算角点x的{​​{1}}和y坐标?


1-4

2 个答案:

答案 0 :(得分:1)

最后弄清楚了,在线上有很多不同的方式,但没有一种有效。反复试验赢得了胜利。


const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;
const halfWidth = width / 2;

// changed only this function
function getCorner(point, angle, length) {
  angle = angle * (Math.PI / 180);

  return {
    x: point.x + Math.sin(angle) * length,
    y: point.y + Math.cos(angle) * length
  };
}

// EXPECTED
// bottom left: {x: 0, y: 5}
// bottom right: {x: 0, y: -5}
// top left: {x: 10, y: 5}
// top right: {x: 10, y: -5}

console.log(
  "bottom left:", 
  getCorner(A, direction - 90, halfWidth)
);

// here's an error with JS or something, because
// "x: 6.123233995736766e-16" which is
// "0.0000000000000006123233995736766"
console.log(
  "bottom right:", 
  getCorner(A, direction + 90, halfWidth)
);

console.log("---");

console.log(
  "top left:", 
  getCorner(B, direction - 90, halfWidth)
);
console.log(
  "top right:", 
  getCorner(B, direction + 90, halfWidth)
);

答案 1 :(得分:1)

通过指示Y轴向上,可以简单地解决以下问题:

enter image description here

我们看到每个拐角点都位于AB段周围+/- 90度角处。考虑下图,很容易计算dxdy值(从A或B到每个拐角点):

dx = (W/2).sin(alpha)
dy = (W/2).cos(alpha)

其中alpha等于90 - direction。因此,我们可以按照以下代码段编写js代码:

const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;

var length = width / 2;
var angle = (90 - direction) * (Math.PI / 180);

var dx = Math.sin(angle) * length;
var dy = Math.cos(angle) * length;

console.log( "bottom left:", {x: A.x - dx, y: A.y + dy} );
console.log( "bottom right:",  {x: A.x + dx, y: A.y - dy} );
console.log("---");
console.log( "top left:",  {x: B.x - dx, y: B.y + dy} );
console.log( "top right:",  {x: B.x + dx, y: B.y - dy} );