Movement

31 Dec, 2018 - Notes

A naive approach to implement AI movement, and one I see people often run into problems with, is to just do the following:

while(true){
    if(x < targetx){
        x += 1;
    }
    else if(x > targetx){
        x -= 1;
    }
    else{
        // reached target
    }
}
(this can easily be extended into higher dimensions by doing the same for y,z,etc)

This will work, and will actually work perfectly when you are using integers for everything, but let’s say for example that x is non-integer value such as 0.5 and targetx is 1, for example.

Since x < targetx is true, x += 1 will be executed, making x now 1.5. On the next iteration, x > targetx is true and so x -= 1 will be executed, making x now 0.5 again. This will then keep repeating forever, making the movement direction to constantly flip every frame, resulting in a weird vibrating sort of motion.

In other words, the step distance (of 1 in this case) is too large, and keeps over-stepping the actual position!

The solution is simple, really. When the distance from the target is smaller than the step, you can just essentially step directly to the target position (woe teleportation). Here’s an implementation of this below:

while(true){
    if(x+1 < targetx){
        x += 1;
    }
    else if(x-1 > targetx){
        x -= 1;
    }
    else{
        x = targetx;
        // reached target
    }
}

Better Movement

The above movement code is linear and makes the movement look unnatural (though it may be good enough for a lot of cases). You can make the movement look more beautiful by modelling the movement with a non-linear function (make it ease in and ease out). Below is the equation I used for the AI in this project, for example: