improve this float RLBotBot::calculateMinAirTime(const Vec& playerPos, const Vec& playerVel, bool hasFlip) {
constexpr float GRAVITY = 650.0f; // Units per second squared (adjust based on game physics)
code
// Initialize simulation parameters
float t = 0.0f;
Vec pos = playerPos;
Vec vel = playerVel;
float timeToGround = std::numeric_limits<float>::infinity();
float timeToSideWall = std::numeric_limits<float>::infinity();
float timeToBackWall = std::numeric_limits<float>::infinity();
float timeToCeiling = std::numeric_limits<float>::infinity();
// Simulate the player's trajectory over time
while (t < MAX_PREDICTION_TIME) {
// Update position and velocity
// Only vertical velocity is affected by gravity
pos.z += vel.z * TIME_STEP + 0.5f * (-GRAVITY) * TIME_STEP * TIME_STEP;
vel.z += (-GRAVITY) * TIME_STEP;
pos.x += vel.x * TIME_STEP;
pos.y += vel.y * TIME_STEP;
// Check for ground collision
if (pos.z <= CommonValues::BALL_RADIUS) { // Assuming ground is at z = 0
timeToGround = t;
break; // Ground collision is the earliest possible
}
// Check for ceiling collision
if (vel.z > 0.0f && pos.z + CommonValues::BALL_RADIUS >= CommonValues::CEILING_Z) {
timeToCeiling = t;
// Do not break; the player might hit the ceiling before the ground
// But ground collision is prioritized
break;
}
// Check for side wall collision
if (vel.x != 0.0f) {
float timeToCurrentSideWall = 0.0f;
if (vel.x > 0.0f) {
timeToCurrentSideWall = (CommonValues::SIDE_WALL_X - pos.x - CommonValues::BALL_RADIUS) / vel.x;
}
else {
timeToCurrentSideWall = (-CommonValues::SIDE_WALL_X - pos.x + CommonValues::BALL_RADIUS) / vel.x;
}
if (timeToCurrentSideWall >= 0.0f && timeToCurrentSideWall <= TIME_STEP) {
timeToSideWall = t;
//RG_LOG(timeToSideWall);
break;
}
}
// Check for back wall collision
if (vel.y != 0.0f) {
float timeToCurrentBackWall = 0.0f;
if (vel.y > 0.0f) {
timeToCurrentBackWall = (CommonValues::BACK_WALL_Y - pos.y - CommonValues::BALL_RADIUS) / vel.y;
}
else {
timeToCurrentBackWall = (-CommonValues::BACK_WALL_Y - pos.y + CommonValues::BALL_RADIUS) / vel.y;
}
if (timeToCurrentBackWall >= 0.0f && timeToCurrentBackWall <= TIME_STEP) {
timeToBackWall = t;
//RG_LOG(timeToBackWall);
break;
}
}
// Increment time
t += TIME_STEP;
}
// Determine the minimum time among all collision possibilities
float minAirTime = RS_MIN(timeToGround, timeToSideWall, timeToBackWall, timeToCeiling);
// Ensure the minimum air time is not negative or NaN
if (minAirTime < 0.0f || std::isnan(minAirTime)) {
minAirTime = 0.0f;
}
return minAirTime;
const auto& car = gs.players[this->index];
const auto& ball = gs.ball;
Vec carPos = car.phys.pos;
Vec carVel = car.phys.vel;
Vec targetPos = ball.pos;
Vec dirToTarget = (targetPos - carPos).Normalized();
float dist = (targetPos - carPos).Length();
float vel = carVel.Dot(dirToTarget);
float rotTime = calculateRotationTime(gs);
// Calculate the minimum time to land on any surface
float minAirTime = calculateMinAirTime(carPos, carVel, car.hasFlip);
RG_LOG(minAirTime);
float t = 0.0f;
float curDist = dist;
float curVel = vel;
Vec pos = carPos;
Vec curVelVec = carVel;
// Simulate air time
for (; t < minAirTime && curDist > DIST_REACH_THRESH; t += STEP_INTERVAL) {
// Update position and velocity
pos += curVelVec * STEP_INTERVAL;
curVelVec.z += -GRAVITY * STEP_INTERVAL;
if (t == 0.0f && curVel < MAX_TOTAL_SPEED) {
// Apply flip force only at the beginning
curVelVec += dirToTarget * (FLIP_FORCE * STEP_INTERVAL);
}
curVel = curVelVec.Dot(dirToTarget);
curDist = (targetPos - pos).Length();
}
// After landing: apply acceleration logic
for (; curDist > DIST_REACH_THRESH; t += STEP_INTERVAL) {
bool hasRotated = t >= rotTime;
if (curVel < 0.0f) {
curVel += (BREAK_ACCEL + BOOST_ACCEL * hasRotated) * STEP_INTERVAL;
curVel = RS_CLAMP(curVel, -MAX_TOTAL_SPEED, MAX_TOTAL_SPEED);
}
else if (curVel < MAX_DRIVE_SPEED) {
curVel += (DRIVE_ACCEL + BOOST_ACCEL * hasRotated) * STEP_INTERVAL;
curVel = RS_CLAMP(curVel, 0.0f, MAX_DRIVE_SPEED);
}
else if (curVel < MAX_TOTAL_SPEED) {
curVel += BOOST_ACCEL * hasRotated * STEP_INTERVAL;
curVel = RS_CLAMP(curVel, 0.0f, MAX_TOTAL_SPEED);
}
curDist -= curVel * STEP_INTERVAL;
}
return t;
} calculate minimum time to the nearest surface first
fredrik.. — 08/03/2024 9:50 PM
so if its on the wall i first calculate the time to ground then time too ball?
thats pretty smart
Zealan — 08/03/2024 9:52 PM
its hard though
because what if the optimal landing spot isnt the fastest landing spot
but a landing spot closer to the ball
fredrik.. — 08/03/2024 9:52 PM
damn
how did you solve that then?
Zealan — 08/03/2024 9:52 PM
minimum case assumptions minimum case just means we combine the minimum possible answer from multiple cases
to make a combined answer that might be too low, but cant be too highwell we have multiple cases
going in the air to the ball
landing from the air and driving to the ball
its not obvious where to land though
or if its worth it at all
however under minimum cases, we assume that they reach a surface in their minimum surface reach time, then we assume they accelerate on that surface until they reach the ball, even if the minumum reach point isnt at the ball yet
Certainly! To enhance the calculateMinAirTime function, we can shift from a simulation-based approach to an analytical one. This change will improve both the accuracy and efficiency of the calculation. Additionally, I'll address some inconsistencies and potential issues in the original implementation.
Key Improvements:
Analytical Collision Time Calculation: Instead of iterating through time steps to detect collisions, we can analytically solve for the time when the player will collide with the ground, ceiling, or walls. This approach reduces computational overhead and increases precision.
Handling Multiple Collisions: By calculating collision times for all potential surfaces independently, we ensure that the earliest collision time is correctly identified, avoiding premature termination of the simulation loop.
Code Clarity and Robustness: Improved variable naming, structured logic, and comprehensive error handling make the code more readable and maintainable.
Improved calculateMinAirTime Function
cpp
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
float RLBotBot::calculateMinAirTime(const Vec& playerPos, const Vec& playerVel, bool hasFlip) {
constexpr float GRAVITY = 650.0f; // Units per second squared (adjust based on game physics)
constexpr float BALL_RADIUS = CommonValues::BALL_RADIUS;
constexpr float CEILING_Z = CommonValues::CEILING_Z;
constexpr float SIDE_WALL_X = CommonValues::SIDE_WALL_X;
constexpr float BACK_WALL_Y = CommonValues::BACK_WALL_Y;
constexpr float MAX_PREDICTION_TIME = 10.0f; // Adjust as needed
std::vector<float> collisionTimes;
// Helper lambda to solve quadratic equations: a*t^2 + b*t + c = 0
auto solveQuadratic = [](float a, float b, float c) -> std::vector<float> {
std::vector<float> roots;
float discriminant = b * b - 4.0f * a * c;
if (discriminant < 0.0f) {
return roots; // No real roots
}
float sqrtD = std::sqrt(discriminant);
float t1 = (-b - sqrtD) / (2.0f * a);
float t2 = (-b + sqrtD) / (2.0f * a);
if (t1 >= 0.0f) roots.push_back(t1);
if (t2 >= 0.0f) roots.push_back(t2);
return roots;
};
// 1. Time to Ground Collision
{
float a = -0.5f * GRAVITY;
float b = playerVel.z;
float c = playerPos.z - BALL_RADIUS;
std::vector<float> roots = solveQuadratic(a, b, c);
if (!roots.empty()) {
float t_ground = *std::min_element(roots.begin(), roots.end());
if (t_ground <= MAX_PREDICTION_TIME) {
collisionTimes.push_back(t_ground);
}
}
}
// 2. Time to Ceiling Collision
if (playerVel.z > 0.0f) { // Only if moving upward
float targetZ = CEILING_Z - BALL_RADIUS;
float a = -0.5f * GRAVITY;
float b = playerVel.z;
float c = playerPos.z - targetZ;
std::vector<float> roots = solveQuadratic(a, b, c);
if (!roots.empty()) {
float t_ceiling = *std::min_element(roots.begin(), roots.end());
if (t_ceiling <= MAX_PREDICTION_TIME) {
collisionTimes.push_back(t_ceiling);
}
}
}
// 3. Time to Side Wall Collision (X-axis)
if (playerVel.x != 0.0f) {
float targetX;
if (playerVel.x > 0.0f) {
targetX = SIDE_WALL_X - BALL_RADIUS;
} else {
targetX = -SIDE_WALL_X + BALL_RADIUS;
}
float t_wall_x = (targetX - playerPos.x) / playerVel.x;
if (t_wall_x >= 0.0f && t_wall_x <= MAX_PREDICTION_TIME) {
collisionTimes.push_back(t_wall_x);
}
}
// 4. Time to Back Wall Collision (Y-axis)
if (playerVel.y != 0.0f) {
float targetY;
if (playerVel.y > 0.0f) {
targetY = BACK_WALL_Y - BALL_RADIUS;
} else {
targetY = -BACK_WALL_Y + BALL_RADIUS;
}
float t_wall_y = (targetY - playerPos.y) / playerVel.y;
if (t_wall_y >= 0.0f && t_wall_y <= MAX_PREDICTION_TIME) {
collisionTimes.push_back(t_wall_y);
}
}
// Determine the minimum collision time
float minAirTime = std::numeric_limits<float>::infinity();
for (const float& t : collisionTimes) {
if (t < minAirTime) {
minAirTime = t;
}
}
// Clamp the result
if (minAirTime < 0.0f || std::isnan(minAirTime)) {
minAirTime = 0.0f;
} else if (minAirTime > MAX_PREDICTION_TIME) {
minAirTime = MAX_PREDICTION_TIME;
}
return minAirTime;
}
Explanation of Improvements
Analytical Collision Time Calculation:
Ground and Ceiling Collisions: We solve the quadratic equation derived from the vertical motion to find the exact time when the player will collide with the ground or ceiling. This eliminates the need for iterative simulation.
Wall Collisions: For side and back walls (X and Y axes), we perform straightforward linear calculations since motion in these directions is uniform (no acceleration).
Collision Time Collection:
All potential collision times are collected in the collisionTimes vector. We then iterate through this vector to find the smallest positive collision time, ensuring that we capture the earliest collision event.
Lambda Function for Quadratic Solutions:
A helper lambda solveQuadratic is defined to solve quadratic equations and return valid (non-negative) roots, simplifying the main function's logic.
Conditional Checks:
Ceiling Collision: Only calculated if the vertical velocity (playerVel.z) is positive, meaning the player is moving upward.
Wall Collisions: Only calculated if there's a non-zero velocity component in the respective direction.
Clamping and Validation:
The final minAirTime is clamped to MAX_PREDICTION_TIME to avoid excessively long predictions.
Negative or NaN values are clamped to 0.0f to ensure valid return values.
Code Readability and Maintainability:
Clear variable names and structured blocks for each collision type enhance readability.
Comprehensive comments explain each step, making future maintenance easier.
Potential Further Enhancements
Dynamic Boundaries: If the game arena has dynamic boundaries or additional obstacles, you may need to incorporate their positions and dimensions into the collision time calculations.
Rotation and Flip Mechanics: Although hasFlip is a parameter, it's not utilized in this function. Depending on game mechanics, you might want to factor in how flips affect velocity or collision behavior.
Precision Considerations: Ensure that floating-point precision is sufficient for the game's scale to avoid unexpected collisions or missed events.
Conclusion
By switching to an analytical approach, the calculateMinAirTime function becomes more efficient and accurate. This method ensures that all potential collisions are considered, and the earliest collision time is correctly identified without unnecessary iterative computations.
Feel free to integrate this improved function into your codebase and adjust the constants (GRAVITY, BALL_RADIUS, CEILING_Z, SIDE_WALL_X, BACK_WALL_Y, MAX_PREDICTION_TIME) as per your game's physics specifications.