I’m struggling with AI for an enemy in my scrolling shoot-em up game. The player moves continously along the Y axis and objects/enemies spawn from the top of the screen and move downwards towards the player…I have a boss which spawns but would like it to stop moving once it gets say, halfway down the screen, I have looked at measuring distance and such but having problems…pseud code would be something like:
if(distance between boss + player > mindistance){
boss increases speed to prevent falling of bottom of screen
}
else
{keep moving towards player
}
You can use Vector3.Distance(position1, position2). Or, use Vector2, if your game is fully 2d. It’s probably reasonable to do this every frame, e.g. every Update().
If you happen to also need the direction from one thing to another, you can subtract the transform.position of one thing from another to get the vector between them. Then you can that vector’s .magnitude to get the distance.
Another way would be to put a collider on one of them, set as a trigger, size it to the distance you’re concerned with, and have a script on it watch for OnTriggerEnter. Then check for some appropriate identifier on things entering the trigger, such as a tag or component that is only on the thing you’re checking distance to.