Flyer AI for top-down game, picking random points within distances and angle

Greetings,

I’m trying to make an AI movement script for a flying enemy in a top-down game, and I could use some help and an example on a certain part. The idea is:

-The enemy spawns, it goes looking for a target. (Which I’ve already set up how it does that), the position of that target will be the ‘center’.

-It moves towards the center, once within a certain distance, it’s wandering behavior starts.

-This is the hard part: It needs to find a random point within a min and max distance from it’s own transform.position, but it also needs to be within a max distance from the center. And to prevent it doing strange U-turns, it would search within a 90° angle (or another set angle) so it doesn’t pick points behind it.

-Once a point is found, start turning and moving towards it. Once close enough to that point, pick a new one.

I hope that’s clear enough to understand :p. I’ve looked around a bit, found a few topics that are similar to what I’m trying to do, although I still have little idea of how I’m going to handle to hard part. So I’d like to see help and an example, because there are probably many ways to do it, and not all being equally efficient or difficult.

Note: the Y (height) of the flyer is/should be constant, so the waypoints will always have the same height as the object’s height.

Thanks

You might wanna take a look at Unity’s ‘Random.insideUnitSphere’ to calculate a position within a given distance.

You could try something along those lines…

public Vector3 origin, randomPosition;
public int searched;

// The maximum distance to each point
public float maxDistance = 15.0f;

// The amount of points
public int searchPoint = 5;

public void Initialize () {
    // Buffer the position
    origin = transform.position;

    // A random position
    randomPosition = (Random.insideUnitSphere * maxDistance) + origin;

    // The amount of random positions already visited
    searched = 0;
}

public void Do () {
    if (searched < searchPoints) {
            if (Vector3.Distance (transform.position, randomPosition) <= 1) {
                // A new random position
                randomPosition = (Random.insideUnitSphere * maxDistance) + origin;

                // Increase the amount of searched positions
                searched++;
            }
       
            // MOVE THE TARGET TO THE RANDOM POSITION
            // YOUR MOVEMENT CODE HERE :smile:
        }
}