javascript - 如何计算从我的对象到旋转线的最近点
问题描述
做一个这样的小游戏:
https ://bijanmoudi.github.io/teeter-totter/
我的目标是计算从我的对象到线的偏移量
我试图学习如何计算碰撞权但是 -不成功
感谢您的反馈
解决方案
在计算线段与点之间的距离时,首先需要计算穿过该线段的无限线上的最近点。其次,将最近的点夹在线段的范围内。第三,计算从夹紧点到原始点的距离。
const line = [{x:0,y:0}, {x:10, y:0}]
const point1 = {x:2, y:2}
const point2 = {x:-10, y:2}
const point3 = {x:11, y:-1}
function nearestPointDistance(line, point){
//Get the Ax+By+c = 0 representtion of the line
let vector = {x:line[1].x-line[0].x, y:line[1].y-line[0].y}
lineLength = Math.sqrt(vector.x**2 + vector.y**2)
let normalizedVector = {x:vector.x/lineLength, y:vector.y/lineLength}
let pointVector = {x:point.x - line[0].x,y:point.y - line[0].y}
let dotProduct = vector.x*pointVector.x+vector.y*pointVector.y;
dotProduct /= lineLength
let nearestPoint
if(dotProduct < 0)
nearestPoint = line[0];
else if(dotProduct > lineLength)
nearestPoint = line[1];
else nearestPoint = {x:(line[0].x + normalizedVector.x*dotProduct), y:(line[0].y + normalizedVector.y/dotProduct)}
let distance = Math.sqrt((nearestPoint.x - point.x)**2 + (nearestPoint.y - point.y)**2)
return distance;
}
console.log(nearestPoint(line, point1))
console.log(nearestPoint(line, point2))
console.log(nearestPoint(line, point3))
推荐阅读
- java - 自动生成更多 PDF 页面
- javascript - 使用 getSongBPM 时 $.getJSON 不起作用
- php - AWS Lambda 和 Symfony Bref - 部署 Symfony 4 网站
- function - 混合类/对象和函数:代码异味?
- python - 使用一个记录器和多个几乎相同的文件处理程序
- firebase - Firebase 安全规则:允许读取 + 写入除单个集合之外的所有内容
- javascript - JSX 中的多个 If 条件
- python - 有什么理由不使用自动提交吗?
- python - 散景图未嵌入 html
- android - 如何通过自定义 LayoutManager 在 recyclerview 中使用 snapHelper