Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


Should all of the agent's rays be of the same length?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
22 replies to this topic

#1 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 22 April 2011 - 04:05 PM

I'm having some problems with obstacle avoidance and I was wondering if it had anything to do with the length of each of the rays around the agent?

Should my feeler rays be the same length in all directions or proportionally longer in the direction of the agent's velocity?

I currently extend all the rays, regardless of their direction, based on the agent's velocity:


        /// <summary>
        /// Steers the agent to avoid moving obstacles lying in its path
        /// </summary>
        /// <returns></returns>
        private Vector3 ObstacleAvoidance()
        {
            List<RayCastResult> results = new List<RayCastResult>();
            Vector3 steeringForce = new Vector3();

            // Feeler length is proportional to the agent's velocity
            float speed = agent.Velocity.Length();
            float ooMaxSpeed = 1f / agent.MaxSpeed;
            float feelerLength = speed * ooMaxSpeed * minFeelerLength;
            feelerLength += minFeelerLength;

            // For each one of the agent's feelers
            for (int i = 0; i < numFeelers; ++i)
            {
                // Clear the list in preparation for the new ray cast
                results.Clear();

                if (game.Space.RayCast(feelers[i], feelerLength, results))
                {
                    float earliestTime = float.MaxValue;
                    EntityCollidable entityHit = null;
                    int index = 0;

                    int numHit = results.Count;

                    for (int ii = 0; ii < numHit; ++ii)
                    {
                        EntityCollidable e = results[ii].HitObject as EntityCollidable;

                        // Ignore non EntityCollidables
                        // Ignore feeler collision with the agent
                        // Keep the earliest time of collision
                        if (e != null && e.Entity.Tag != agent && results[ii].HitData.T < earliestTime)
                        {
                            earliestTime = results[ii].HitData.T;
                            entityHit = e;
                            index = ii;
                        }
                    }

                    if (entityHit == null)
                    {
                        // Nothing to avoid
                        continue;
                    }
                    else
                    {
                        // [2.5D]
                        Vector3 offset = agent.Position - results[index].HitData.Location;
                        
                        // 'PerpendicularComponent' method
                        float projection = Vector3.Dot(offset, agent.Forward);

                        Vector3 avoidance = offset - (agent.Forward * projection);
                        avoidance.Normalize();
                        avoidance *= agent.MaxSpeed;
                        avoidance += agent.Forward * agent.MaxSpeed * 0.75f;                    
                        avoidance -= agent.Velocity;
                        
                        steeringForce += avoidance;
                    }
                }
            }

            return steeringForce;
        }

However, this produces violent shaking of the agent and not smooth obstacle avoidance:

Video of shaking behaviour


Should I take the dot product of the ray direction and the direction of the velocity and only extend by a multiple of the dot product? (Values less than 0 would be 0)

Sponsor:

#2 IADaveMark   Moderators   -  Reputation: 2533

Like
0Likes
Like

Posted 24 April 2011 - 08:25 AM

Easy answer to question... how do YOU do it when YOU navigate? What do YOU care about?
Dave Mark - President and Lead Designer of Intrinsic Algorithm LLC

Professional consultant on game AI, mathematical modeling, simulation modeling
Co-advisor of the GDC AI Summit
Co-founder of the AI Game Programmers Guild
Author of the book, Behavioral Mathematics for Game AI

Blogs I write:
IA News - What's happening at IA | IA on AI - AI news and notes | Post-Play'em - Observations on AI of games I play

"Reducing the world to mathematical equations!"

#3 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 24 April 2011 - 08:53 AM

I would care about my velocity relative to the velocities of the objects around me. Is that what you are getting at?

Also, why my AI is constantly jerking from side to side when avoiding obstacles?

#4 SimonH   Members   -  Reputation: 133

Like
0Likes
Like

Posted 24 April 2011 - 09:24 AM

The jerking motion is caused by corners falling in the gaps between rays - use more rays (try 30 instead of 10) or concentrate your 10 rays in the direction of travel.
I'd use variable length rays, longer at the front and shorter at the back and sides. See Red3D for more ideas.
Stickmen Wars 2 is in development.
Meanwhile try Bloodridge

#5 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 24 April 2011 - 02:48 PM

The jerking motion is caused by corners falling in the gaps between rays - use more rays (try 30 instead of 10) or concentrate your 10 rays in the direction of travel.


I've upped the number rays to 100 and recorded video with a better frame rate which I have uploaded on YouTube here.

The jerking motion is still there and I'm unsure why as I would have thought 100 rays would be overkill.

The movement of the AI using path finding (without obstacle avoidance) is very smooth as it uses SLERP-ing between orientations:


            // Linear movement
            Vector3 force = steering.Update(gameTime);
            entity.LinearVelocity += force;

            // Angular movement
            if (entity.LinearVelocity.LengthSquared() > MathTools.EPSILON)
            {
                // Store current orientation before calculating new orientation
                //currentOrientation = entity.Orientation;

                // Calculate new orientation based on current velocity
                Matrix rotation = new Matrix();
                rotation.Forward = Vector3.Normalize(entity.LinearVelocity);
                rotation.Up = Vector3.UnitY;
                rotation.Right = Vector3.Cross(rotation.Forward, rotation.Up);

                destOrientation = Quaternion.CreateFromRotationMatrix(rotation);
                destForward = rotation.Forward;
            }

            // Calculate turn rate         
            float angleBetweenVelocities = MathTools.UnsignedAngleBetween3DVectors(entity.OrientationMatrix.Forward, destForward);

            // Only turn if the angle between the current forward and the new forward is greater than 0 (allowing for numerical errors)
            if (angleBetweenVelocities > MathTools.EPSILON)
            {
                // Limit the interpolation amount based on the turn rate
                float maxTurnAngle = turnRate * dtSeconds;
                float amount = MathTools.Clamp(maxTurnAngle / angleBetweenVelocities, 0f, 1f);

                // Set new orientation using SLERP
                entity.Orientation = Quaternion.Slerp(entity.Orientation, destOrientation, amount); //currentOrientation
            }

What else could be the cause?

#6 SimonH   Members   -  Reputation: 133

Like
0Likes
Like

Posted 24 April 2011 - 05:49 PM

100 rays should certainly do it. OK, so I was wrong about the corners...
Looking at the video I wondering if it's not because of your variable ray length - that seems twitchy too... How does it behave if you fix the ray length to max_velocity*2?
PS I found this pdf on fuzzy navigation some of which you might find interesting.
Stickmen Wars 2 is in development.
Meanwhile try Bloodridge

#7 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 24 April 2011 - 06:22 PM

I'll take a look at the pdf you linked to see if that gives some insight into the problem.

If I keep the ray length constant in all directions:

float feelerLength = agent.MaxSpeed * 2f;

then it makes no difference to the twitchy movement.

I'm completely out of ideas as to how to solve this one. It seems especially odd that this would occur considering that I've ported the obstacle avoidance method from the Steer/Red3D source code.

#8 jbadams   Senior Staff   -  Reputation: 19418

Like
0Likes
Like

Posted 24 April 2011 - 09:19 PM

You're trying to move forwards along a certain path -- why do you care about objects that are behind or beside you?

You care about objects that are in front of you, or that are going to be in front of you.

Concentrate your rays to the front and sides of the object, focussing particularly in front. Unless you're planning on very sudden drastic turns or reversing you shouldn't care what's behind you at all; you'll find out about those things when/if you turn around.


To me it looks like the shaking in your current implementation is the result of your agent reacting to objects that aren't in the way; because you're casting a ray to the side the agent detects that there is an object next to it and attempts to steer away from it, even though it would not have hit said item simply by continuing it's current path.

#9 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 25 April 2011 - 05:16 AM

To me it looks like the shaking in your current implementation is the result of your agent reacting to objects that aren't in the way; because you're casting a ray to the side the agent detects that there is an object next to it and attempts to steer away from it, even though it would not have hit said item simply by continuing it's current path.


I've uploaded another video here showing the agent with all the rays concentrated in the direction of the current velocity. The agent still shakes from side to side but I think I have an idea of what might be causing it.

In my code all the feelers are iterated through and the closest object for each feeler will have an affect on the velocity. The problem is that the effect on the velocity will be the same whether the object is 10 units away or 1 unit away:


                        Vector3 offset = agent.Position - results[index].HitData.Location;
                        
                        // 'PerpendicularComponent' method
                        float projection = Vector3.Dot(offset, agent.Forward);

                        Vector3 avoidance = offset - (agent.Forward * projection);
                        avoidance.Normalize();                                                                                                  // Same force no matter what distance.
                        avoidance *= agent.MaxSpeed;
                        avoidance += agent.Forward * agent.MaxSpeed * 0.75f;                    
                        avoidance -= agent.Velocity;
                        
                        steeringForce += avoidance;

How can I use the length of the offset to scale the avoidance force correctly and should the 'steeringForce' be an accumulation of all the avoidance forces for all the objects in contact with every feeler?

#10 IADaveMark   Moderators   -  Reputation: 2533

Like
1Likes
Like

Posted 25 April 2011 - 08:23 AM

Do you realize you can get a lot of mileage out of shooting one feeler ray per frame in a random direction in a cone in front of you? This 100 rays thing seems like incredible overkill and certainly won't scale very well.
Dave Mark - President and Lead Designer of Intrinsic Algorithm LLC

Professional consultant on game AI, mathematical modeling, simulation modeling
Co-advisor of the GDC AI Summit
Co-founder of the AI Game Programmers Guild
Author of the book, Behavioral Mathematics for Game AI

Blogs I write:
IA News - What's happening at IA | IA on AI - AI news and notes | Post-Play'em - Observations on AI of games I play

"Reducing the world to mathematical equations!"

#11 SimonH   Members   -  Reputation: 133

Like
0Likes
Like

Posted 25 April 2011 - 11:18 AM

How can I use the length of the offset to scale the avoidance force correctly and should the 'steeringForce' be an accumulation of all the avoidance forces for all the objects in contact with every feeler?

This is where the fuzzy logic comes in - for each ray you 'fuzzify' the input using a 'membership function' to get an attraction rating (eg for the path/food/whatever - values from 0 to 1) and an obstacle rating (for obstacles/enemies/etc - again 0 to 1). You subtract obstacle from attraction for all rays, and the ray left with the highest value shows the way you want to go. You can see this in action here (unfortunately I can't find the source code).
Stickmen Wars 2 is in development.
Meanwhile try Bloodridge

#12 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 25 April 2011 - 11:23 AM

Do you realize you can get a lot of mileage out of shooting one feeler ray per frame in a random direction in a cone in front of you?




I didn't before you mentioned it, thanks Dave.

Based on your advice I'm now using the following method to generate a random ray (one per frame) inside a conical area:


        /// <summary>
        /// Creates a specified number of random rays within a conical shape denoted by the attitude and heading ranges
        /// </summary>
        /// <param name="origin">Origin of all the rays generated</param>
        /// <param name="forward">Direction around which the random rays will be generated</param>
        /// <param name="attitudeRange">Attitude (up down) angle over which to distribute the rays [Radians]</param>
        /// <param name="headingRange">Heading (left right) angle over which to distribute the rays [Radians]</param>
        /// <param name="numRays">Number of rays to generate</param>
        /// <returns>The random rays generated by the method</returns>
        public static Microsoft.Xna.Framework.Ray[] RandomRayCone(Vector3 origin, Vector3 forward, float attitudeRange, float headingRange, int numRays)
        {
            // See: http://mathworld.wolfram.com/SphericalCoordinates.html

            // r = radial = radius from a point to the origin
            // theta = heading = azimuthal
            // phi = attitude = polar/zenith/colatitude  

            // [Z = Up]
            // x = r * cosTheta * sinPhi
            // y = r * sinTheta * sinPhi
            // z = r * cosPhi

            // phi = cos^-1(z / r) = Math.Acos(z / r)
            // theta = tan^-1(y / x) = Math.Atan2(y / x)

            // [Y = Up]
            // 'y' and 'z' are swapped

            Microsoft.Xna.Framework.Ray[] rays = new Microsoft.Xna.Framework.Ray[numRays];

            float currentAttitude = (float)Math.Acos(forward.Y / forward.Length());
            float currentHeading = (float)Math.Atan2(forward.Z, forward.X);

            attitudeRange *= 0.5f;
            headingRange *= 0.5f;

            float minAttitude = currentAttitude - attitudeRange;
            float maxAttitude = currentAttitude + attitudeRange;

            float minHeading = currentHeading - headingRange;
            float maxHeading = currentHeading + headingRange;

            for (int i = 0; i < numRays; ++i)
            {
                // Create a random direction for the ray within the attitude and heading ranges
                currentAttitude = Random.NextFloat(minAttitude, maxAttitude);
                currentHeading = Random.NextFloat(minHeading, maxHeading);
                
                forward.X = (float)Math.Cos(currentHeading) * (float)Math.Sin(currentAttitude);
                forward.Y = (float)Math.Cos(currentAttitude);
                forward.Z = (float)Math.Sin(currentHeading) * (float)Math.Sin(currentAttitude);

                // Create the ray
                rays[i] = new Microsoft.Xna.Framework.Ray(origin, forward);
            }

            return rays;
        }

The method works great but was written by myself. If the terminology could be improved upon then I would grateful if someone could correct it.

I've uploaded another video here of the results. The agent still has jittery movement in its and it will also pass through some obstacles with this new method.

#13 IADaveMark   Moderators   -  Reputation: 2533

Like
0Likes
Like

Posted 25 April 2011 - 11:42 AM


Do you realize you can get a lot of mileage out of shooting one feeler ray per frame in a random direction in a cone in front of you?



I didn't before you mentioned it, thanks Dave.


That's why I'm here, sir.

I've uploaded another video here of the results. The agent still has jittery movement in its and it will also pass through some obstacles with this new method.


Seems like the rays are far too long. You really only need to look about a second out in front of you.

Without bothering to look at your code, I would also say that the jitteryness is more a function of how much course correction you are doing and how quickly you are slerping. At this point, the obstacle detection is in place and the result really only needs to know what state you are in: Clear, Obstacle left, Obstacle right. Based on that and the distance to the obstacle, you can do some sliding-scale adjustments.

There is also some more un-complicated math in play based on the ANGLE of the "wall" that is presented to you. Is it sloping away from you or towards you? If it is sloping away, then you want to turn slightly so as to run parallel to it. If it is sloping towards you when you detect it, you actually want to turn in the direction of the hit.

For example, imagine going down a hall. If you your feeler hits the right wall, you turn left to stay in the middle. That wall was sloping away from you.

On the other hand, if you were headed almost perpendicular to the wall, you might have a feeler on your left that hits the wall, but the correct direction to correct is TO the LEFT. The way to determine this is to cast a 2nd ray straight out your nose (only when your feeler hits something). Compare the two lengths (the feeler and the nose ray) and see which one is longer. That way, you can tell the orientation of the wall compared to your current direction of travel. THAT is why you are seeing some of the jitteryness when you are approaching obstacles perpendicularly... the rays that alternate on either side of your direction are both hitting the same target and feeding conflicting information about which way to turn.



Dave Mark - President and Lead Designer of Intrinsic Algorithm LLC

Professional consultant on game AI, mathematical modeling, simulation modeling
Co-advisor of the GDC AI Summit
Co-founder of the AI Game Programmers Guild
Author of the book, Behavioral Mathematics for Game AI

Blogs I write:
IA News - What's happening at IA | IA on AI - AI news and notes | Post-Play'em - Observations on AI of games I play

"Reducing the world to mathematical equations!"

#14 xEricx   Members   -  Reputation: 564

Like
0Likes
Like

Posted 25 April 2011 - 01:50 PM

It's always fun to "reinvent the wheel", but you can use existing "wheels" as a reference.

Check out OpenSteer, it solves the dynamic avoidance problem and way more: http://opensteer.sourceforge.net/

Cheers

#15 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 25 April 2011 - 02:34 PM

Check out OpenSteer, it solves the dynamic avoidance problem and way more: http://opensteer.sourceforge.net/

My obstacle avoidance code is taken directly from that source code:

Open Steer:

        // compute avoidance steering force: take offset from obstacle to me,
        // take the component of that which is lateral (perpendicular to my
        // forward direction), set length to maxForce, add a bit of forward
        // component (in capture the flag, we never want to slow down)
        const Vec3 offset = position() - nearest.obstacle->center;
        avoidance = offset.perpendicularComponent (forward());
        avoidance = avoidance.normalize ();
        avoidance *= maxForce ();
        avoidance += forward() * maxForce () * 0.75;


My Implementation:

                        // [2.5D]
                        Vector3 offset = agent.Position - results[index].HitData.Location;
                        offset.Y = 0f;
                        
                        // 'PerpendicularComponent' method
                        float projection = Vector3.Dot(offset, agent.Forward);

                        Vector3 avoidance = offset - (agent.Forward * projection);
                        avoidance.Normalize();
                        avoidance *= agent.MaxSpeed;
                        avoidance += agent.Forward * agent.MaxSpeed * 0.75f;                    
                        avoidance -= agent.Velocity;
                        
                        steeringForce += avoidance;


I would also say that the jitteryness is more a function of how much course correction you are doing and how quickly you are slerping



I'm currently slerping using a turn rate of 4 radians per second:


            // Calculate turn rate         
            float angleBetweenVelocities = MathTools.UnsignedAngleBetween3DVectors(entity.OrientationMatrix.Forward, destForward);

            // Only turn if the angle between the current forward and the new forward is greater than 0 (allowing for numerical errors)
            if (angleBetweenVelocities > MathTools.EPSILON)
            {
                // Limit the interpolation amount based on the turn rate
                float maxTurnAngle = turnRate * dtSeconds;
                float amount = MathTools.Clamp(maxTurnAngle / angleBetweenVelocities, 0f, 1f);

                // Set new orientation using SLERP
                entity.Orientation = Quaternion.Slerp(entity.Orientation, destOrientation, amount); //currentOrientation
            }


If I lower that to 0.5f then the same jerky movements are apparent but the agent doesn't turn as quickly. See this video for an example.

Based on that and the distance to the obstacle, you can do some sliding-scale adjustments



If the course correction is the issue, how would the distance affect the adjustments mathematically?

There is also some more un-complicated math in play based on the ANGLE of the "wall" that is presented to you. Is it sloping away from you or towards you? If it is sloping away, then you want to turn slightly so as to run parallel to it. If it is sloping towards you when you detect it, you actually want to turn in the direction of the hit.



I've set up the code to detect the obstacle directly in front of the agent but it won't work correctly without the correct scaling:


                       // Entity has been hit, raycast in forward direction of agent
                        List<RayCastResult> forwardResults = new List<RayCastResult>();

                        if (game.Space.RayCast(new Microsoft.Xna.Framework.Ray(agent.Position, agent.Forward), feelerLength, forwardResults))
                        {
                            float tForward = float.MaxValue;
                            int numHitForwards = results.Count;

                            // Iterate through all the objects hit and only keep store the earliest time of collision
                            for (int ii = 0; ii < numHitForwards; ++ii)
                            {
                                EntityCollidable e = results[ii].HitObject as EntityCollidable;

                                // Ignore non EntityCollidables
                                // Ignore feeler collision with the agent
                                // Keep the earliest time of collision
                                if (e != null && e.Entity.Tag != agent && results[ii].HitData.T < tForward)
                                {
                                    tForward = results[ii].HitData.T;
                                }
                            }

                            if (entityHit != null)
                            {
                                // The shorter ray will determine whether the obstacle is facing away from or towards the agent
                                if (tForward > tFeeler)
                                {

                                }
                                else
                                {

                                }
                            }
                        }


#16 IADaveMark   Moderators   -  Reputation: 2533

Like
0Likes
Like

Posted 25 April 2011 - 04:54 PM

If the course correction is the issue, how would the distance affect the adjustments mathematically?

If the distance to the object is farther, your rate of turn can be slower.

Dave Mark - President and Lead Designer of Intrinsic Algorithm LLC

Professional consultant on game AI, mathematical modeling, simulation modeling
Co-advisor of the GDC AI Summit
Co-founder of the AI Game Programmers Guild
Author of the book, Behavioral Mathematics for Game AI

Blogs I write:
IA News - What's happening at IA | IA on AI - AI news and notes | Post-Play'em - Observations on AI of games I play

"Reducing the world to mathematical equations!"

#17 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 25 April 2011 - 04:58 PM

If the distance to the object is farther, your rate of turn can be slower.


but the jerky movement still occurs with a slower turn rate, as shown in the last video.

Could the following line cause a problem:

avoidance -= agent.Velocity;

I ask because it is not included in the OpenSteer source code but causes the agent to move way too fast without it.

#18 LorenzoGatti   Crossbones+   -  Reputation: 2779

Like
0Likes
Like

Posted 26 April 2011 - 04:25 AM

Can't you stabilize the system by "shooting" a whole cone (in 2D a triangle) in front of the agent?

The nearest obstacle in the cone can be either the middle of a contour, in which case you can decide to turn left or right (possibly preferring your current steering direction and/or the direction that requires the least steering to clear the obstacle), or a corner (with a tangent through your current position that falls in the cone) which would usually be cleared by steering towards the tangent.
Produci, consuma, crepa

#19 xEricx   Members   -  Reputation: 564

Like
1Likes
Like

Posted 26 April 2011 - 06:41 AM


If the distance to the object is farther, your rate of turn can be slower.


but the jerky movement still occurs with a slower turn rate, as shown in the last video.

Could the following line cause a problem:

avoidance -= agent.Velocity;

I ask because it is not included in the OpenSteer source code but causes the agent to move way too fast without it.


Well, steering shouldn't make you accelerate over your maximum velocity. Everytime I've written a steering component (it's been a while though, so I might be missing some details) I made it return 2 things:
1) heading
2) braking factor

The braking factor can be optional, depending on the feel you want to have. In the examples you showed, you just need to modify the heading of your cube.

If I understand correctly in the code you posted destForward is steeringForce? If so, from what you posted you only use it to calculate a turn angle, how would it make the agent move way too fast? Have you tried clamping your velocity to your max velocity?

#20 Spa8nky   Members   -  Reputation: 230

Like
0Likes
Like

Posted 26 April 2011 - 09:27 AM

Have you tried clamping your velocity to your max velocity?


I'm currently using this method to clamp the velocity:


        /// <summary>
        /// Clamps the length of a given vector to 'maxLength'
        /// </summary>
        /// <param name="v">Vector to clamp</param>
        /// <param name="maxLength">Length to which to clamp the vector to</param>
        /// <returns>Clamped vector</returns>
        public static Vector3 TruncateLength(this Vector3 v, float maxLength)
        {
            float maxLengthSquared = maxLength * maxLength;
            float vLengthSquared = v.LengthSquared();

            return vLengthSquared <= maxLengthSquared ? v : v * (maxLength / (float)Math.Sqrt(vLengthSquared));
        }

If I understand correctly in the code you posted destForward is steeringForce?



The force returned is the steering force but I have been using it to drive the linear velocity, which then in turn affects the angular velocity. I think this must be where I am going wrong!

The linear velocity/movement comes from calculating the steering:


            // Linear movement
            Vector3 force = steering.Update(gameTime);
            entity.LinearVelocity += force;

which is then used to determine the heading:


            // Angular movement
            if (entity.LinearVelocity.LengthSquared() > MathTools.EPSILON)
            {
                // Store current orientation before calculating new orientation
                //currentOrientation = entity.Orientation;

                // Calculate new orientation based on current velocity
                Matrix rotation = new Matrix();
                rotation.Forward = Vector3.Normalize(entity.LinearVelocity);
                rotation.Up = Vector3.UnitY;
                rotation.Right = Vector3.Cross(rotation.Forward, rotation.Up);

                destOrientation = Quaternion.CreateFromRotationMatrix(rotation);
                destForward = rotation.Forward;
            }

            // Calculate turn rate         
            float angleBetweenVelocities = MathTools.UnsignedAngleBetween3DVectors(entity.OrientationMatrix.Forward, destForward);

            // Only turn if the angle between the current forward and the new forward is greater than 0 (allowing for numerical errors)
            if (angleBetweenVelocities > MathTools.EPSILON)
            {
                // Limit the interpolation amount based on the turn rate
                float maxTurnAngle = turnRate * dtSeconds;
                float amount = MathTools.Clamp(maxTurnAngle / angleBetweenVelocities, 0f, 1f);

                // Set new orientation using SLERP
                entity.Orientation = Quaternion.Slerp(entity.Orientation, destOrientation, amount); //currentOrientation
            }

Should the linear velocity be constant unless a braking force is returned?

If so, from what you posted you only use it to calculate a turn angle, how would it make the agent move way too fast?


By making the mistakes I have outlined above?

So after the light has switched on in my brain, this is how I think I should be calculating the agent's movement:


            // Calculate steering force
            Vector3 force = steering.Update(gameTime);

            // Angular movement
            if (force.LengthSquared() > MathTools.EPSILON)
            {
                // Calculate new orientation based on current steering force
                Matrix rotation = new Matrix();
                rotation.Forward = Vector3.Normalize(force);
                rotation.Up = Vector3.UnitY;
                rotation.Right = Vector3.Cross(rotation.Forward, rotation.Up);

                destOrientation = Quaternion.CreateFromRotationMatrix(rotation);
                destForward = rotation.Forward;
            }

            // Calculate turn rate         
            float angleBetweenVelocities = MathTools.UnsignedAngleBetween3DVectors(entity.OrientationMatrix.Forward, destForward);

            // Only turn if the angle between the current forward and the new forward is greater than 0 (allowing for numerical errors)
            if (angleBetweenVelocities > MathTools.EPSILON)
            {
                // Limit the interpolation amount based on the turn rate
                float maxTurnAngle = turnRate * dtSeconds;
                float amount = MathTools.Clamp(maxTurnAngle / angleBetweenVelocities, 0f, 1f);

                // Set new orientation using SLERP
                entity.Orientation = Quaternion.Slerp(entity.Orientation, destOrientation, amount); //currentOrientation
            }

            // Linear movement
            entity.LinearVelocity = entity.OrientationMatrix.Forward * maxSpeed;

Now I would also need to return a braking force, otherwise the agent is constantly moving at its maximum speed.

Am I on the right track with this?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS