Question

I'm writing a small space game, but I'm stuck at moving my ship in a nice way from point A to point B in open 2D space.

My first problem with the solution below is that my ship never comes to a complete stop. It gets close, but it keeps vibrating around point B forever. My second problem is that if I snap it to B when it gets close, the sudden stop looks fake and bad as well.

I think I would like the ship to speed up, travel and slow down just before it stops exactly at point B without any bouncing, but I have no idea how to accomplish that in a good way. Also, if there is some "right" way to move a ship from point A to point B in 2D space that I haven't considered, other ideas are very welcome.

if(player.x < destination.x) {
    if(player.velocityX < player.speed) {
        player.velocityX += 10;         
    }
} else {
    if(player.velocityX > -player.speed) {
        player.velocityX -= 10;
    }
}

if(player.y < destination.y) {
    if(player.velocityY < player.speed) {
        player.velocityY += 10;         
    }
} else {
    if(player.velocityY > -player.speed) {
        player.velocityY -= 10;
    }
}

// Friction.
player.velocityX *= 0.9;
player.velocityY *= 0.9;

player.x += player.velocityX;
player.y += player.velocityY;

Note that this solution doesn't use trigonometric functions for a straight path from A to B yet, but that shouldn't affect the question I think.

Any help would be very appreciated!

Was it helpful?

Solution

I ended up with a solution where I increase the Friction once the player passed it's destination point, making the ship finally slow down to 0 without snapping to point B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top