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

标签 javascript html5-canvas

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

现在我总是将 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
}

关于javascript - HTML 5 Canvas 以相同的速度在定义的线上移动圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67179694/

相关文章:

HTML5 Canvas 图像向左旋转 向右旋转

javascript - 使用鼠标在 html5 canvas 中水平和垂直倾斜绘图

javascript - NodeJS cronjob 中未调用 Mongoose 查询回调

javascript - 使用 javascript 获取 AspNet.ApplicationCookie

javascript - 从学位类(class)中解析文本方式的类(class)?

javascript - 使用 JavaScript 或 jQuery 监听 Youtube 事件

javascript - 如果浏览发生在同一窗口同一选项卡中,请使用 js/java 检查

javascript - 为什么canvas和webgl渲染器不一样? (三.js)

javascript - 在html中播放wav音频文件的移动波形

jquery - 如何让涟漪更明显?