HTML5画布:沿着定义的直线以相同速度移动的圆形

3
我有一个具体的问题。我有两个矩形,正在计算这两个矩形之间的线。现在我想在该线上画一个圆,该圆以特定速度向前移动。我总是使用新坐标重新绘制圆来实现运动。
现在,我总是将圆的x坐标加1,然后用我的方程计算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;

点击链接查看图片,了解我的计算和思路

1个回答

1

单位向量

使用线的单位(规范化)向量。规范化向量始终为一个单位长度(除非该线段没有长度)。您可以按需缩放向量的速度。

标准化线段

示例 ? 应为数字。

// 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
}

非常感谢,它完美地运行了 :) - Henning

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接