计算从当前位置向目标位置移动一定距离后的位置

/**
 * 计算从当前位置向目标位置移动一定距离后的位置
 * @param moveDistance: 移动距离
 * @param curPosX, curPosY: 当前位置
 * @param aimPosX, aimPosY: 目标位置
 */
public calNextPos(moveDistance, curPosX, curPosY, aimPosX, aimPosY) {
    let distance = Math.sqrt(Math.pow(aimPosX - curPosX, 2) + Math.pow(aimPosY - aimPosY, 2))
    let offsetY = moveDistance * (curPosY - aimPosY) / distance
    let nextPosY = curPosY - offsetY
    let nextPosX = this.binaryEquationGetX(curPosX, curPosY, aimPosX, aimPosY, nextPosY)
    return { x: nextPosX, y: nextPosY }
}
/**
 * 求二元一次方程的系数
 * y1 = k * x1 + b => k = (y1 - b) / x1
 * y2 = k * x2 + b => y2 = ((y1 - b) / x1) * x2 + b
 */
private binaryEquationGetKB(x1, y1, x2, y2) {
    let k = (y1 - y2) / (x1 - x2)
    let b = (x1 * y2 - x2 * y1) / (x1 - x2)
    return [k, b]
}
/**
 * 二元一次方程:根据y求x
 */
public binaryEquationGetX(x1, y1, x2, y2, y) {
    let kbArr = this.binaryEquationGetKB(x1, y1, x2, y2)
    let k = kbArr[0]
    let b = kbArr[1]
    return (y - b) / k
}

猜你喜欢

转载自www.cnblogs.com/H-K-Home/p/10058680.html