Your goal is to make the agent perform smooth turns when the target point is behind or not directly in front of it. While your overall approach is logical, there are a few issues in the code that could prevent the desired smooth turning behavior. Let's break down the potential problems and suggest improvements:
1. Calculation of targetPos in findTurnPoint
The findTurnPoint lambda function is responsible for calculating a new target position (m_TurnPoint) for the agent to navigate around obstacles or to change direction smoothly. The current implementation of targetPos calculation for both left and right turns is quite complex and might be mathematically incorrect.
Issues:
- Complex Formula: The formula used to calculate
targetPos is convoluted and may not correctly position the turn point relative to the agent's current orientation.
- Angle Step Misuse:
m_TurnDegreeStep is set to 120 degrees, which is a large step for a smooth turn. This could cause abrupt changes in direction rather than smooth transitions.
- Consistent Direction Handling: The left and right turn calculations might not be symmetric or correctly mirror each other, leading to inconsistent turning behaviors.
Suggested Improvement:
-
Simplify Turn Calculation: Use a more straightforward method to calculate the turn point based on the agent's orientation and desired turn radius. For instance, offset the current position perpendicular to the agent's orientation by the turn radius in the desired direction (left or right).
glm::vec3 perpendicular = glm::normalize(glm::cross(m_AgentOrientation, glm::vec3(0, 1, 0)));
if (cross.y < 0) { // Turn left
targetPos = currentPos + perpendicular * m_TurnRadius;
} else { // Turn right
targetPos = currentPos - perpendicular * m_TurnRadius;
}
-
Adjust m_TurnDegreeStep: Consider using a smaller angle step, such as 30 or 45 degrees, to allow for smoother turns.
2. Handling stuckTime
The stuckTime variable is intended to keep track of how long the agent has been stuck, enabling it to apply random offsets to escape potential obstacles or dead-ends.
Issue:
stuckTime Not Updated: In the provided code, stuckTime is declared as a static variable but never updated within the UpdateMainAgent function. This means the condition if (stuckTime > 1.0f) will never be true, and the random offset logic will never execute.
Suggested Improvement:
-
Increment stuckTime: Update the stuckTime variable based on whether the agent is making progress towards the target.
// At the beginning of the update function
if (glm::length(m_PathFindingEnd - currentPos) < some_threshold) {
stuckTime += dt;
} else {
stuckTime = 0.0f;
}
3. Managing the m_IsTurning Flag
The m_IsTurning flag is used to determine whether the agent is currently in the process of turning.
Issue:
- Potential for Being Stuck in Turning State: If the angle condition to stop turning is not met correctly, the agent might remain in the turning state indefinitely, especially if
angleToReal never falls below m_TurnAngleThreshold.
Suggested Improvement:
- Ensure Correct Angle Calculation: Verify that
angleToReal accurately reflects the desired condition to exit the turning state.
- Add Safeguards: Implement additional checks or timeouts to reset
m_IsTurning if the agent does not reach a satisfactory orientation within a reasonable timeframe.
4. Use of Static Variables
Using static variables within the UpdateMainAgent function means that these variables retain their values between function calls, which is appropriate for maintaining state. However, this can lead to issues if multiple agents are involved or if the function is called in a context where these variables need to reset.
Issue:
- Single Agent Limitation: If your system evolves to handle multiple agents, static variables will not suffice as they are shared across all calls to the function.
Suggested Improvement:
-
Use Member Variables: Instead of declaring these variables as static within the function, consider making them member variables of the VictoriaPhysics class. This approach ensures that each agent has its own state.
// In VictoriaPhysics.h
class VictoriaPhysics {
public:
void UpdateMainAgent(float dt);
private:
glm::vec3 m_AgentOrientation;
float stuckTime;
bool m_IsTurning;
glm::vec3 m_RealDestination;
glm::vec3 m_TurnPoint;
// Other members...
};
5. Angle Calculation Using acos
The use of glm::acos can lead to precision issues, especially when dealing with floating-point inaccuracies that might push the dot product slightly outside the valid range of [-1, 1].
Issue:
- Potential for NaN Results: If
glm::dot(m_AgentOrientation, glm::normalize(toTarget)) exceeds 1.0 or is less than -1.0 due to floating-point errors, glm::acos will return NaN, causing unexpected behavior.
Suggested Improvement:
-
Clamp the Dot Product: Ensure that the dot product is clamped within the [-1, 1] range before calling glm::acos.
float dotProduct = glm::dot(m_AgentOrientation, glm::normalize(toTarget));
dotProduct = glm::clamp(dotProduct, -1.0f, 1.0f);
float angle = glm::degrees(glm::acos(dotProduct));
6. Ensuring Navigation Mesh Validity
After computing the m_TurnPoint, you attempt to find the nearest polygon on the navigation mesh. If findNearestPoly fails or returns an unexpected result, the agent may not navigate correctly.
Issue:
- No Check for Valid Poly Reference: There’s no validation to ensure that
nearestRef and nearestPos are valid after calling findNearestPoly.
Suggested Improvement:
-
Validate nearestRef: Check whether findNearestPoly successfully found a valid polygon reference before proceeding.
if (m_NavMeshBuilder->GetNavMeshQuery()->findNearestPoly(&targetPos.x, polyPickExt, &filter, &nearestRef, nearestPos)) {
return glm::vec3(nearestPos[0], nearestPos[1], nearestPos[2]);
} else {
// Handle failure (e.g., set a fallback turn point or stop turning)
return currentPos;
}
Revised Code Snippet
Here's a revised version of the UpdateMainAgent function incorporating the suggested improvements:
void VictoriaPhysics::UpdateMainAgent(float dt) {
// Member variables instead of static
if (!initialized) { // Initialize member variables in constructor or an init method
m_AgentOrientation = glm::vec3(1, 0, 0);
stuckTime = 0;
m_IsTurning = false;
// Initialize other members...
initialized = true;
}
if (m_Crowd && m_IsMoving) {
dtCrowdAgent* ag = m_Crowd->getEditableAgent(m_MainActorId);
if (ag && ag->active) {
glm::vec3 currentPos(ag->npos[0], ag->npos[1], ag->npos[2]);
glm::vec3 currentVel(ag->vel[0], ag->vel[1], ag->vel[2]);
float polyPickExt[3] = { 0.5f, 2.0f, 0.5f };
if (glm::length2(currentVel) > 0.001f) {
m_AgentOrientation = glm::normalize(currentVel);
}
ag->params.separationWeight = 0.01f;
ag->params.maxSpeed = 5.0f;
ag->params.maxAcceleration = 40.0f;
ag->params.collisionQueryRange = ag->params.radius * 1.0f;
dtQueryFilter filter;
filter.setIncludeFlags(SAMPLE_POLYFLAGS_WALK ^ SAMPLE_POLYFLAGS_JUMP);
filter.setExcludeFlags(SAMPLE_POLYFLAGS_SWIM);
filter.setAreaCost(SAMPLE_POLYAREA_WATER, 65534);
if (glm::length2(m_PathFindingEnd) > 0.001f) {
glm::vec3 targetPos(m_PathFindingEnd);
glm::vec3 toTarget = targetPos - currentPos;
toTarget.y = 0; // Ignore vertical difference
if (glm::length(toTarget) < some_small_threshold) {
// Handle very close target (optional)
}
float dotProduct = glm::dot(m_AgentOrientation, glm::normalize(toTarget));
dotProduct = glm::clamp(dotProduct, -1.0f, 1.0f);
float angle = glm::degrees(glm::acos(dotProduct));
auto findTurnPoint = [&](const glm::vec3& realDest) -> glm::vec3 {
glm::vec3 direction = glm::normalize(realDest - currentPos);
glm::vec3 perpendicular = glm::normalize(glm::cross(m_AgentOrientation, glm::vec3(0, 1, 0)));
glm::vec3 targetPos;
if (glm::dot(glm::cross(m_AgentOrientation, direction), glm::vec3(0, 1, 0)) < 0) {
// Turn left
targetPos = currentPos + perpendicular * m_TurnRadius;
} else {
// Turn right
targetPos = currentPos - perpendicular * m_TurnRadius;
}
dtPolyRef nearestRef;
float nearestPos[3];
if (m_NavMeshBuilder->GetNavMeshQuery()->findNearestPoly(&targetPos.x, polyPickExt, &filter, &nearestRef, nearestPos)) {
return glm::vec3(nearestPos[0], nearestPos[1], nearestPos[2]);
} else {
// Fallback if no valid poly found
return currentPos;
}
};
auto handleTurning = [&]() {
if (glm::distance(currentPos, m_TurnPoint) <= ag->params.radius * 1.2f) {
glm::vec3 toRealDest = glm::normalize(m_RealDestination - currentPos);
float angleToReal = glm::degrees(glm::acos(glm::clamp(glm::dot(m_AgentOrientation, toRealDest), -1.0f, 1.0f)));
if (angleToReal > m_TurnAngleThreshold) {
m_TurnPoint = findTurnPoint(m_RealDestination);
} else {
m_IsTurning = false;
float pos[3] = { m_RealDestination.x, m_RealDestination.y, m_RealDestination.z };
dtPolyRef nearestRef;
float nearestPos[3];
if (m_NavMeshBuilder->GetNavMeshQuery()->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, nearestPos)) {
m_Crowd->requestMoveTarget(m_MainActorId, nearestRef, nearestPos);
}
return;
}
}
float pos[3] = { m_TurnPoint.x, m_TurnPoint.y, m_TurnPoint.z };
dtPolyRef nearestRef;
float nearestPos[3];
if (m_NavMeshBuilder->GetNavMeshQuery()->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, nearestPos)) {
m_Crowd->requestMoveTarget(m_MainActorId, nearestRef, nearestPos);
}
};
// Update stuckTime based on movement
if (glm::length(toTarget) < some_threshold) {
stuckTime += dt;
} else {
stuckTime = 0.0f;
}
if (angle > m_TurnAngleThreshold && !m_IsTurning) {
m_RealDestination = targetPos;
m_IsTurning = true;
m_TurnPoint = findTurnPoint(m_RealDestination);
}
if (m_IsTurning) {
handleTurning();
} else {
// Normal movement
float pos[3] = { targetPos.x, targetPos.y, targetPos.z };
dtPolyRef nearestRef;
float nearestPos[3];
if (m_NavMeshBuilder->GetNavMeshQuery()->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, nearestPos)) {
if (stuckTime > 1.0f) {
float randomOffset = 0.5f;
nearestPos[0] += ((float)rand() / RAND_MAX * 2 - 1) * randomOffset;
nearestPos[2] += ((float)rand() / RAND_MAX * 2 - 1) * randomOffset;
}
m_Crowd->requestMoveTarget(m_MainActorId, nearestRef, nearestPos);
}
}
}
} else {
m_IsMoving = false;
}
}
if (m_Crowd) {
m_Crowd->update(dt / 1000.0f, nullptr);
}
}
Summary of Key Changes:
-
Simplified findTurnPoint: The turn point is calculated by offsetting the current position perpendicular to the agent's orientation based on the turn radius and direction (left/right).
-
Clamped Dot Product: Ensures that the value passed to acos is within the valid range to prevent NaN results.
-
Updated stuckTime: Incremented based on the agent's progress towards the target to enable the stuck handling mechanism.
-
Moved Static Variables to Member Variables: This change ensures that each agent can maintain its own state independently, which is crucial for scalability.
-
Validation of findNearestPoly: Added checks to ensure that a valid polygon reference is found before proceeding with movement commands.
-
Smaller Turn Steps: Adjusted m_TurnDegreeStep to a smaller value (e.g., 30 or 45 degrees) for smoother turns.
Final Recommendations:
-
Debugging: Add logging or debugging statements to monitor the values of key variables like angle, m_IsTurning, m_TurnPoint, etc., to ensure they are being updated as expected.
-
Testing with Different Parameters: Experiment with different values for m_TurnRadius, m_TurnAngleThreshold, and m_TurnDegreeStep to find the combination that yields the smoothest turning behavior for your specific use case.
-
Visual Debugging: If possible, visualize the agent's path and turning points within your development environment to better understand how the agent is navigating and to identify any discrepancies in the turning logic.
By addressing these issues and implementing the suggested improvements, your agent should exhibit the smooth turning behavior you’re aiming for when the target is behind or not directly in front.