首页 > 解决方案 > 根据距离和方向计算坐标

问题描述

这是我方便的方案:

在此处输入图像描述

鉴于:

如何计算xy坐标角1-4


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

// tried the following one that I found but
// no lock, I assume somethings off with angles
function getCorner(point, angle, length) {
  return {
    x: point.x + Math.cos(angle) * length,
    y: point.y + Math.sin(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)
);
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)
);

标签: javascript

解决方案


终于弄明白了,网上有这么多不同的方法,没有一个奏效。反复试验赢得了胜利。


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)
);


推荐阅读