• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Spa8nky

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

22 posts in this topic

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:

[code]

/// <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;
}
[/code]

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

[url="http://screencast.com/t/z7WVOKNgQ"]Video of shaking behaviour[/url]


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)
0

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites
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 [url="http://www.red3d.com/cwr/steer/Obstacle.html"]Red3D[/url] for more ideas.
0

Share this post


Link to post
Share on other sites
[quote name='SimonH' timestamp='1303658668' post='4802321']
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.
[/quote]

I've upped the number rays to 100 and recorded video with a better frame rate which I have uploaded on YouTube [url="http://www.youtube.com/watch?v=4k6lo2G3kjY"]here[/url].

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:

[code]

// 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
}
[/code]

What else could be the cause?
0

Share this post


Link to post
Share on other sites
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 [url="http://www.cs.csubak.edu/%7Ewli/Wei_Li_Pub/IEEE_MFI94_Li.pdf"]fuzzy navigation[/url] some of which you might find interesting.
0

Share this post


Link to post
Share on other sites
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:

[code]
float feelerLength = agent.MaxSpeed * 2f;
[/code]

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

Share this post


Link to post
Share on other sites
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 [i]front[/i] of you, or that are [i]going to be in front[/i] 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.
0

Share this post


Link to post
Share on other sites
[quote name='jbadams' timestamp='1303701550' post='4802533']
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.
[/quote]

I've uploaded another video [url="http://www.youtube.com/watch?v=G7-5kTNoDhM"]here[/url] 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:

[code]

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;
[/code]

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?
0

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites
[quote name='Spa8nky' timestamp='1303730198' post='4802614']
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?[/quote]
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 [u][url="http://www.hayles.demon.co.uk/fow/fow.html"]here[/url][/u] (unfortunately I can't find the source code).
0

Share this post


Link to post
Share on other sites
[quote]
[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? [/size][/color]
[color=#1C2837][size=2][/quote][/size][/color]
[color=#1C2837][size=2]
[/size][/color]
[color=#1C2837][size=2]I didn't before you mentioned it, thanks Dave.[/size][/color]

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

[code]

/// <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;
}
[/code]

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 [url="http://www.youtube.com/watch?v=kNNuTompbU8"]here[/url] of the results. The agent still has jittery movement in its and it will also pass through some obstacles with this new method.
0

Share this post


Link to post
Share on other sites
[quote name='Spa8nky' timestamp='1303752200' post='4802723']
[quote]
[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? [/size][/color]
[color="#1C2837"][size="2"][/quote][/size][/color]
[color="#1C2837"] [/color]
[color="#1C2837"][size="2"]I didn't before you mentioned it, thanks Dave.[/size][/color]
[size="2"][color="#1C2837"][/quote][/color][/size]
[size="2"][color="#1C2837"]That's why I'm here, sir.
[color=#000000][size=3][quote][/size][/color][/color][/size]I've uploaded another video [url="http://www.youtube.com/watch?v=kNNuTompbU8"]here[/url] 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.


0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
[quote name='xEricx' timestamp='1303761005' post='4802791']Check out OpenSteer, it solves the dynamic avoidance problem and way more: http://opensteer.sourceforge.net/[/quote]My obstacle avoidance code is taken directly from that source code:

Open Steer:

[code]
// 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;
[/code]

My Implementation:

[code]
// [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;
[/code]


[quote name='IADaveMark' ]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[/quote]

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

[code]

// 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
}
[/code]


If I lower that to 0.5f then the same jerky movements are apparent but the agent doesn't turn as quickly. See [url="http://www.youtube.com/watch?v=75Vfha9kRU4"]this[/url] video for an example.

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

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

[code]

// 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
{

}
}
}
[/code]
0

Share this post


Link to post
Share on other sites
[quote name='Spa8nky' timestamp='1303763678' post='4802807']
If the course correction is the issue, how would the distance affect the adjustments mathematically?
[/quote]
If the distance to the object is farther, your rate of turn can be slower.
0

Share this post


Link to post
Share on other sites
[quote name='IADaveMark' timestamp='1303772077' post='4802853']
If the distance to the object is farther, your rate of turn can be slower.
[/quote]

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

Could the following line cause a problem:

[code]
avoidance -= agent.Velocity;
[/code]

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

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
[quote name='Spa8nky' timestamp='1303772298' post='4802856']
[quote name='IADaveMark' timestamp='1303772077' post='4802853']
If the distance to the object is farther, your rate of turn can be slower.
[/quote]

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

Could the following line cause a problem:

[code]
avoidance -= agent.Velocity;
[/code]

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?
1

Share this post


Link to post
Share on other sites
[quote name='xEricx' timestamp='1303821686' post='4803028']
Have you tried clamping your velocity to your max velocity?
[/quote]

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

[code]

/// <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));
}
[/code]
[quote]
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:

[code]

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

which is then used to determine the heading:

[code]

// 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
}
[/code]

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

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

[code]

// 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;
[/code]

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?
0

Share this post


Link to post
Share on other sites
I have no experiencing with this, so forgive my input if its plain silly but often an uninitiated eye can catch things right? My thought in reading the thread is that your updating every frame right? so buffer the updates, don't take immediate feedback and apply it, average it and filter it for extremes or inputs that go against the norm, then after maybe 10 or 20 frames return the smoothed out data as an input to turn. In other words clear out the erroneous data between the feeler return and the input to the actor, I would think creating a data set of returns and finding a norm would be the best way to go about it. Find the number of frames it takes to get from the end of the feeler to obstacles and use a third of those frames, more or less, to smooth out movement. You do this with your new code checking for negative input, and adjusting interpolation, but I think you should be setting up a buffer where turns are checked against multiple inputs not just the immediate turn. You could do this before or after getting the actual turn rate.

Make your actor think more before he turns.
0

Share this post


Link to post
Share on other sites
I'm using a similar avoidance behavior at the moment and attributed the jerkiness to the fact that high turning speeds will lead the agent to turn away from obstacles very fast so Its path is "clear" for the next time step. In the next step it figures "ah nothing in the way" and will again turn hard to its destination etc. I guess one could solve this by not allowing instant angular velocity changes but using angular acceleration and maximum angular velocity to describe turning motion. That should automatically smooth out the jerkiness.
0

Share this post


Link to post
Share on other sites
Another thing you can do with the 2-feeler method is to determine the angle at which the obstacle is facing toward or away from you. By doing so, you can set your new heading as parallel to the plane of the obstacle.

Additionally, one reason for using sliding scale techniques on the length of the feelers... change the turn rate based on how far away the obstacle is. The closer it is, the quicker you want to turn to the new heading. Also, if the obstacle is inside a certain time distance (not just physical distance), you can also reduce your speed. This give it a "whoa!" factor as well.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0