Calculating with vectors in game loop causes fps drop

I am trying to implement Artificial intelligence in my actionScript3 game using vectors from box2d. I am copying vector, multiplying, normalizing ... 10 times each update and because of so much calculations game starts to lagg. How do i reduce that lagg, bescause game almost freezes. Is that a bug or i am not doing it right.

Code: Select all

for (var i:int = 0; i < obstacles.length; i++)
         {
            var velocityTemp:b2Vec2 = velocity.Copy();
            velocityTemp.Normalize();
            var forward:b2Vec2 = b2Vec2.Make(velocityTemp.x, velocityTemp.y);
            var diff:b2Vec2 = b2Vec2.Make(obstacles[i].getPosition().Copy().x - position.x,obstacles[i].getPosition().Copy().y - position.y);
            var dotProduct:Number = b2Math.Dot(diff, forward);
            if (dotProduct > 0)
            {
               var ray:b2Vec2 = b2Vec2.Make(forward.Copy().x * 10, forward.Copy().y * 10);
               var projection:b2Vec2 = b2Vec2.Make(forward.Copy().x * dotProduct, forward.Copy().y * dotProduct);
               var dist:b2Vec2 = b2Vec2.Make(projection.Copy().x - diff.x, projection.Copy().y - diff.y);
               var distance:Number = dist.Length();
               ray = null;
               projection = null;
               dist = null;
               distance = 0;
            }
         }
         velocityTemp = null;
         velocity = null;
         position = null;
         forward = null;
         diff = null;
         dotProduct = 0;
      }

I tried setting them all to null but problem still exist.
I'm not sure if this is going to help with the lag problem, but:

When you're just getting the components of vectors, you don't have to copy it. Instead of this:

Code: Select all

var diff:b2Vec2 = b2Vec2.Make(obstacles[i].getPosition().Copy().x - position.x,obstacles[i].getPosition().Copy().y - position.y);

You can just do this:

Code: Select all

var diff:b2Vec2 = b2Vec2.Make(obstacles[i].getPosition().x - position.x, obstacles[i].getPosition().y - position.y);


Everytime you call .Copy(), another b2Vec2 instance is made. You're making 9 instances for every loop the for loop goes through when it really should be just 1.

Also, doing a lot of square roots takes a lot of processing (which is what dist.Length() does), so yeah. If you can, use dist.LengthSquared() instead and do this for comparison:

Code: Select all

if (dist.LengthSquared() < range*range)

which achieves the same effect as this:

Code: Select all

if (dist.Length() < range)


And another thing, depending how you lay out the obstacles (grid, linear, etc.), there are lots of different kinds of optimizations, such as only calculating some of the obstacles if it's in a certain (rectangular) area.

Original thread: https://box2d.org/forum/viewtopic.php?t=9153