HTML 5 Canvas Moving circle on defined line with same speed

Viewed 187

I have a specific question. I have two rectangles and I'm calculating the line between these two rectangles. Now I want to draw a circle on that line, which is moving forward on the line with a specific speed. I'm redrawing the circle always with new coordinates, that's how i solved the movement.

Now I'm adding to the x-coordinate of the Circle always 1 and then calculate the y-coordinate with my equation. There problem here is, the higher my line slope is, the faster the circle moves.

So how can I calculate the x-coordinate, that the speed of the ball is always the same?

Here is my following code. posX and posY are the positions of the ball that I overwrite. Gun and Ammo are my two rectangles.

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

1 Answers

Unit vector

Use the line's Unit (normalized) vector. The normalized vector is always one unit long (unless the line has no length) You can scale the vector to what ever speed you require

Normalize line

Example ? should be numbers

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

Scale vector and add unit vector

To use the vector to move at a constant speed. The speed scales the normal vector.

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