- Home /
Get AI behavior to avoid enclosure walls?
Hi all. I'm trying to work out a concept here and am stuck on what I hope is a somewhat simplistic answer. Working in the X,Y planes only I have a force-driven AI ship wandering around an enclosed area (the black square in the picture). My goal is to make the wandering a bit more intelligent, avoiding the edges of the enclosure. For the record, the enclosure rotates around Z and has thin collision boxes lining each edge. Also, I'm trying to find a solution that will work for enclosures that aren't always going to be the same shape, so also for a circle or a star or something.
In this pic, the ship is the tiny dot near the center with the red, green and blue gizmos sticking out.

My first thought was to make a collision trigger area that would tell the ship 'hey, you're getting too close to the wall'. That's easy enough, but I can't seem to find a way to get the closest wall, find a vector perpendicular to that wall. If I could do that, I could say something like apply force (1/distanceToWall)*RepellingForce or something (pseudo code, of course).
My second thought was setting up individual trigger rectangles for each wall, always putting a force on any ship it affects. That kinda made sense since even when it rotates the local coordinates and axis would rotate with the enclosure, so the top trigger rectangle could apply the force in the -transform.up direction. I still need to figure out distance from the closest point of the wall, though.
Third thought was strictly using something like a raycast, but again, not sure how to find the closest bit of wall relative to the ship.
Any thoughts? I checked out UnitySteer, but wasn't able to get it avoiding anything other than spheres. I'm not sure if I should be looking in to pathfinding meshes and all that jazz? Best I could find for the 'closest to object' was this, but it requires having enough vertices to track. These walls have... 2. One at each end.
Answer by Berenger · Mar 04, 2012 at 12:50 AM
The same idea than the raycast, but more fit to your situation, Physics.OverlapSphere. Call that around the ship, then finding the closest one will be easy (use sqrMagnitude, not the classic magnitude). An array is always returned, so you can check if Length == 0.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i get the IsPathPossible() function to ignore some nodes using Astar Pathfinding Project 0 Answers
How do i get the IsPathPossible() function to ignore some nodes using Astar Pathfinding Project 0 Answers
Basic 2d AI follow? 1 Answer