在地图开发中经常会遇到这样的问题,从一个点出发到另一个点,走了一段距离之后位置在哪,怎么计算?
转换下问题即
已知两点,求距离起点特定距离的点(已知AC,求B点坐标或已知BC,求A点坐标)?
计算过程如下
设:A(x1,y1)C(x2,y2) AB距离L
向量AC:(x2-x1,y2-y1)
sin = (y2-y1)/AC长度
con =(x2-x1)/AC长度
得
B(x1+L * cos ,y1+ L * sin)
代码实现
class vector {
constructor(pointStart, pointEnd) {
this.pointStart = pointStart
this.pointEnd = pointEnd
this.xLength = pointEnd.x - pointStart.x
this.yLength = pointEnd.y - pointStart.y
this.length = Math.sqrt(Math.pow(this.xLength, 2) + Math.pow(this.yLength, 2))
this.cos = this.xLength / this.length
this.sin = this.yLength / this.length
}
getSin() {
return this.sin
}
getCos() {
return this.cos
}
getLength() {
return this.length
}
getStartPoint(length) {
return {
x: this.pointStart.x + length * this.cos,
y: this.pointStart.y + length * this.sin,
}
}
getEndPoint(length) {
let fanlength = this.length - length
return this.getStartPoint(fanlength)
}
}
验证
let pointStart = { x: 1, y: 1 }
let pointEnd = { x: 5, y: 5 }
let v1 = new vector(pointStart, pointEnd)
console.log(`${v1.getStartPoint(4)}`)
console.log(`${v1.getEndPoint(1)}`)
let v2 = new vector(pointEnd, pointStart)
console.log(`${v2.getStartPoint(1)}`)
console.log(`${v2.getEndPoint(4)}`)