HTML 5 Canvas 以相同的速度在定义的直线上移动圆

HTML 5 Canvas Moving circle on defined line with same speed

我有一个具体问题。我有两个矩形,我正在计算这两个矩形之间的线。现在我想在那条直线上画一个圆,它正以特定的速度在直线上向前移动。我总是用新坐标重新绘制圆圈,这就是我解决运动的方法。

现在我总是将 1 添加到圆的 x 坐标,然后使用我的方程式计算 y 坐标。这里有个问题,我的线斜率越高,圆圈移动得越快。

那么如何计算 x 坐标,使球的速度始终相同?

这是我的以下代码。 posX 和 posY 是我覆盖的球的位置。 Gun 和 Ammo 是我的两个矩形。

this.posX = this.posX - 1;
this.posY = ((this.gunY - this.ammoY) / (this.gunX - this.ammoX)) * (this.posX - this.ammoX) + this.ammoY;

image to understand my calculation and my thoughts

单位向量

使用线的单位(归一化)向量。归一化向量始终是一个单位长(除非直线没有长度)您可以将向量缩放到您需要的任何速度

标准化线

示例?应该是数字

// the line start and end
const startX = ?
const startY = ?
const endX = ?
const endY = ?

function getLineNormal() {

    // get the line vector
    const vx = endX - startX
    const vy = endY - startY

    // get the line length
    const len = Math.hypot(vx, vy)

    // Only if the line has length
    if (len > 0) {
        // calculate normal of vector
        return {x: vx / len, y: vy / len}

    } 
    return return {x: 0, y: 0}
}

缩放向量并添加单位向量

使用矢量匀速移动。速度缩放法向量。

// set circle at start of line.
var circleX = startX
var circleY = startY
const lineVec = getLineNormal()

function moveCircle(speed) { // speed in pixels
    circleX += lineVec.x * speed
    circleY += lineVec.y * speed
}