如何计算从我的对象到旋转线的最近点



做这样的迷你游戏:
https://bijanmoudi.github.io/teeter-totter/

图像

我的目标是计算从我的对象到直线的偏移
我试图学习如何计算碰撞权限,但-未成功

感谢您的反馈

您应该计算对象和直线之间的距离,如下所示:

const line = document.getElementsById('line')
const obj = document.getElementsById('obj')
const distance = Math.hypot(obj.position.x - line.position.x, obj.position.y - line.position.y);  

计算线段和点之间的距离时,首先需要计算穿过线段的无限线上最近的点。其次,将最近的点夹在线段的边界内。第三,计算从夹点到原点的距离。

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

最新更新