JPatrickDev
JPatrickDev

Reputation: 95

Smooth movement java

I'm working on some AI stuff in Java. When an entity moves towards a point, the movement does not look natural. If its starting point and target are not equal X and Y distances away from each other, the movement looks like this: Unnatural movement

What I want it to look move like is this: Smoother movement

Currently, movement is done like so:

        int tX = target.x;
        int tY = target.y;

        if(tX> oX){
            getOwner().addX(getOwner().getMoveSpeed());
        }

        if(tX < oX){
            getOwner().addX(-getOwner().getMoveSpeed());
        }

        if(tY> oY){
            getOwner().addY(getOwner().getMoveSpeed());
        }

        if(tY< oY){
            getOwner().addY(-getOwner().getMoveSpeed());
        }

I'm guessing that there is a much better method for handling movement than this.

So what I want to know is probably how to work out the angle I need to move along, and then the x and y velocitys needed to do so.

Upvotes: 0

Views: 924

Answers (2)

Richard Sitze
Richard Sitze

Reputation: 8463

You're describing the process of drawing a line between two points.

There are relatively simple integer-only algorithms, such as Bresenham that may help.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234795

You just need to scale the x and y speeds according to the total distance to be traveled in each direction.

It will help to do the calculations in floating point and round to an int only when you need to assign a position.

int tX = target.x;
int tY = target.y;
float speed = getOwner.getMoveSpeed();
float dX = tX - oX;
float dY = tY - oY;
float dist = Math.sqrt(dX * dX + dY * dY);
float sX = speed * dX / dist;
float sY = speed * dY / dist;

getOwner().addX((int) (sX + 0.5));
getOwner().addY((int) (sY + 0.5));

Upvotes: 6

Related Questions