diff ai/steer.d @ 21:cad384ad349e

avoid
author zzzzrrr <mason.green@gmail.com>
date Thu, 26 Mar 2009 07:02:56 -0400
parents 6efd0830715b
children 4fce5596d1f6
line wrap: on
line diff
--- a/ai/steer.d	Wed Mar 25 15:25:25 2009 -0400
+++ b/ai/steer.d	Thu Mar 26 07:02:56 2009 -0400
@@ -182,6 +182,64 @@
 
         return avoidance;
     }
+    
+    bzVec2 avoid(float minTimeToCollision, bzBody obstacles) {
+        
+        float avoidMargin = 1.0f;
+        float maxLookahead = minTimeToCollision * m_speed;
+        
+        // Make sure we're moving
+		if (m_velocity.length > 0)
+		{
+            for (bzBody o = obstacles; o; o = o.next) {
+            
+                if(o is m_body) continue;
+                
+                // Find the distance from the line we're moving along to the obstacle.
+                bzVec2 movementNormal = m_velocity;
+                movementNormal.normalize();
+                bzVec2 characterToObstacle = o.position - m_position;
+
+                real distanceSquared = bzDot(characterToObstacle, movementNormal);
+                distanceSquared = characterToObstacle.length - 
+                    distanceSquared*distanceSquared;
+
+                // Check for collision
+                // Find radius of obstacle
+                float oRad = 0;
+                for (bzShape shape = o.shapeList; shape; shape = shape.next) {
+                    if(shape.sweepRadius > oRad) {
+                        oRad = shape.sweepRadius;
+                    }
+                }
+                
+                real radius = oRad + avoidMargin;
+                if (distanceSquared < radius*radius)
+                {
+                    // Find how far along our movement vector the closest pass is
+                    real distanceToClosest = bzDot(characterToObstacle, movementNormal);
+                    
+                    // Make sure this isn't behind us and is closer than our lookahead.
+                    if (distanceToClosest > 0 && distanceToClosest < maxLookahead)
+                    {
+                        // Find the closest point
+                        bzVec2 closestPoint = 
+                            o.position + movementNormal*distanceToClosest;
+
+                        // Find the point of avoidance
+                        bzVec2 target = 
+                            o.position +
+                            (closestPoint - o.position).length *
+                            (oRad + avoidMargin);
+
+                        return target;
+                    }
+                }
+            }
+		}
+        return bzVec2.zeroVect;
+
+    }
 
 		void findNextIntersectionWithSphere(bzBody obs, 
                                             inout PathIntersection intersection, float mdc) {