我有一个具体问题。我有两个矩形,我正在计算这两个矩形之间的线。现在我想在那条直线上画一个圆,它正以特定的速度在直线上向前移动。我总是用新坐标重新绘制圆圈,这就是我解决运动的方法。
现在我总是将 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;
最佳答案
单位向量
使用线的单位(归一化)向量。归一化向量始终是一个单位长(除非直线没有长度)您可以将向量缩放到您需要的任何速度
归一化线
例子 ?
应该是数字
// 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/