简体   繁体   中英

How to calculate the closest point from my object to a rotating line

Doing a mini-game like this:
https://bijanmoudi.github.io/teeter-totter/

Image

My goal is to calculate the offset to the line from my object
I tried to learn how to calculate the collision right but - unsuccessful

Appreciate for your feedback

you should calculate the distance between object and line like that:

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

When you calculate the distance between a line segment and point, you first need to calculate the nearest point on the infinite line that runs through the segment. Second, you clamp that nearest point to be within the bounds of the line segment. Third, you calculate the distance from the clamped point to your original point.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM