mkjrfan
mkjrfan

Reputation: 87

How to get Ai to turn slower?

Scenario: I want to make objects follow the player with a given speed. I've made the code that makes the objects follow the player (which works). In order to make the object follow the player I checked what side the object is and then depending on that it would calculate the speed in which it would need to affect the x and y values to make it move in that direction.

Problem: If the player was to get around the Ai the Ai would make sharp turns in order to get to the player. What I want is something to make it the turns less sharply and instead make wider turns.

any questions? Please ask!

My code:

public void facePlayer(){
    double division = (double)Math.abs(player.getY() - enemyy) / Math.abs(player.getX() - enemyx);
    dir = Math.atan(division);      
    dir = lerp(dir,division,spd);
    if (enemyx >= player.getX() && enemyy <= player.getY()) {
        enemyx -= (spd * Math.cos(dir));
        enemyy += (spd * Math.sin(dir));
    }

    //if Coin is top left
    if (enemyx >= player.getX() && enemyy >= player.getY()) {
        enemyx -= (spd * Math.cos(dir));
        enemyy -= (spd * Math.sin(dir));
    }

    //if Coin is bottom right
    if (enemyx <= player.getX() && enemyy <= player.getY()) {
        enemyx += (spd * Math.cos(dir));
        enemyy += (spd * Math.sin(dir));
    }

    //if Coin is bottom left
    if (enemyx <= player.getX() && enemyy >= player.getY()) {
        enemyx += (spd * Math.cos(dir));
        enemyy -= (spd * Math.sin(dir));
    }

}

Upvotes: 0

Views: 109

Answers (3)

kudkudak
kudkudak

Reputation: 496

LERP is one good method.

Another way is taking different point of view. You can add inertia and simple physics. So it cannot change directly its speed, but instead it can only apply force to itself. Think of the player and your object being connected by a spring.

It should naturally make the turns wider, and you will be able to modify it dynamically.

F = versor * constant , where versor is pointing from your object to the player.

Upvotes: 0

Shaun Wild
Shaun Wild

Reputation: 1243

A good way to do it is to use Linear Inerpolition Which is great for stuff like this. A simple LERP function would look like this:

public double lerp(double x, double y, double speed){
    return (y - x) * speed;
}

You could then call this function as:

dir = lerp(dir, newDir, .01);

And then simply decrease/ increase the speed variable until you get it looking just how you want it.

Linear Interpoliton is also very useful when it comes to networking.

Upvotes: 1

superbob
superbob

Reputation: 1638

Don't allow your AI to make 180° turns, remember your last shipDir direction (angle) and allow only 90° turns (+/- 1 to shipDir).

Upvotes: 1

Related Questions