Advertisement

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

Started by April 22, 2011 10:05 PM
21 comments, last by IADaveMark 13 years, 6 months ago

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

[color=#1C2837][size=2]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?
[color=#1C2837][size=2][/quote]
[color=#1C2837][size=2]

[color=#1C2837][size=2]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 = 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.
Advertisement


[color="#1C2837"]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?
[color="#1C2837"]

[color="#1C2837"]
[color="#1C2837"]I didn't before you mentioned it, thanks Dave.
[color="#1C2837"][/quote]
[color="#1C2837"]That's why I'm here, sir.
[color=#000000]

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.
[/quote]

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-founder and 10 year advisor of the GDC AI Summit
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!"

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
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[/quote]

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.[/quote]

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
{

}
}
}

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-founder and 10 year advisor of the GDC AI Summit
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!"

Advertisement

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.
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.

Omae Wa Mou Shindeiru


[quote name='IADaveMark' timestamp='1303772077' post='4802853']
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.
[/quote]

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?

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?
[/quote]


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?
[/quote]

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?

This topic is closed to new replies.

Advertisement