Certainly! Below is a C++ implementation inspired by your provided extrapolation logic. This function calculates the time it takes for a player (car) to reach different surfaces in the game environment—specifically the side walls, back walls, ceiling, and floor. It then identifies and returns the surface that the player will reach in the least amount of time.
Overview
-
Surfaces Defined:
- Side Walls (X-axis): Positioned at
±SIDE_WALL_X.
- Back Walls (Y-axis): Positioned at
±BACK_WALL_Y.
- Ceiling (Z-axis): Positioned at
CEILING_Z.
- Floor (Z-axis): Positioned at
FLOOR_Z.
-
Physics Considerations:
- Horizontal (X & Y): Assuming no acceleration, time is calculated as the distance to the surface divided by the velocity component.
- Vertical (Z): Accounts for gravity, requiring solving a quadratic equation to determine when the player will reach the ceiling or floor.
-
Implementation Steps:
- Calculate Time to Each Surface:
- For Side Walls and Back Walls, use linear extrapolation based on current position and velocity.
- For Ceiling and Floor, solve the quadratic equation considering gravity.
- Determine the Minimum Positive Time: Among all calculated times, select the smallest positive value to identify the next surface the player will reach.
Implementation
#include <cmath>
#include <algorithm>
#include <limits>
#include <optional>
#include <string>
// Define constants
constexpr float SIDE_WALL_X = 4096.0f;
constexpr float BACK_WALL_Y = 5120.0f;
constexpr float CEILING_Z = 2044.0f;
constexpr float FLOOR_Z = 17.0f; // Actual floor height for cars
constexpr float GRAVITY_Z = -650.0f; // Gravity constant
// Enum for surfaces
enum class Surface {
SideWall_PosX,
SideWall_NegX,
BackWall_PosY,
BackWall_NegY,
Ceiling,
Floor
};
// Struct to hold time and corresponding surface
struct SurfaceTime {
float time;
Surface surface;
};
// Function to solve quadratic equations: a*t^2 + b*t + c = 0
std::optional<std::pair<float, float>> SolveQuadratic(float a, float b, float c) {
float discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
return std::nullopt; // No real solutions
}
float sqrt_discriminant = std::sqrt(discriminant);
float t1 = (-b + sqrt_discriminant) / (2 * a);
float t2 = (-b - sqrt_discriminant) / (2 * a);
return std::make_pair(t1, t2);
}
// Function to calculate time to reach surfaces
SurfaceTime CalculateTimeToSurfaces(const Vec& position, const Vec& velocity) {
std::vector<SurfaceTime> surfaceTimes;
const float EPSILON = 1e-6f;
// Time to reach Side Walls (X-axis)
if (std::abs(velocity.x) > EPSILON) {
if (velocity.x > 0) {
float t = (SIDE_WALL_X - position.x) / velocity.x;
if (t >= 0)
surfaceTimes.push_back({ t, Surface::SideWall_PosX });
}
else {
float t = (-SIDE_WALL_X - position.x) / velocity.x;
if (t >= 0)
surfaceTimes.push_back({ t, Surface::SideWall_NegX });
}
}
// Time to reach Back Walls (Y-axis)
if (std::abs(velocity.y) > EPSILON) {
if (velocity.y > 0) {
float t = (BACK_WALL_Y - position.y) / velocity.y;
if (t >= 0)
surfaceTimes.push_back({ t, Surface::BackWall_PosY });
}
else {
float t = (-BACK_WALL_Y - position.y) / velocity.y;
if (t >= 0)
surfaceTimes.push_back({ t, Surface::BackWall_NegY });
}
}
// Time to reach Ceiling (Z-axis)
// Solve: 0.5 * GRAVITY_Z * t^2 + velocity.z * t + (position.z - CEILING_Z) = 0
float a = 0.5f * GRAVITY_Z;
float b = velocity.z;
float c = position.z - CEILING_Z;
auto solutions = SolveQuadratic(a, b, c);
if (solutions.has_value()) {
float t1 = solutions->first;
float t2 = solutions->second;
if (t1 >= 0)
surfaceTimes.push_back({ t1, Surface::Ceiling });
if (t2 >= 0)
surfaceTimes.push_back({ t2, Surface::Ceiling });
}
// Time to reach Floor (Z-axis)
// Solve: 0.5 * GRAVITY_Z * t^2 + velocity.z * t + (position.z - FLOOR_Z) = 0
c = position.z - FLOOR_Z;
solutions = SolveQuadratic(a, b, c);
if (solutions.has_value()) {
float t1 = solutions->first;
float t2 = solutions->second;
if (t1 >= 0)
surfaceTimes.push_back({ t1, Surface::Floor });
if (t2 >= 0)
surfaceTimes.push_back({ t2, Surface::Floor });
}
// Find the minimum positive time
SurfaceTime minSurfaceTime = { std::numeric_limits<float>::max(), Surface::Floor };
for (const auto& st : surfaceTimes) {
if (st.time < minSurfaceTime.time) {
minSurfaceTime = st;
}
}
return minSurfaceTime;
}
// Example Vec structure
struct Vec {
float x;
float y;
float z;
};
// Example PlayerData structure
struct PlayerData {
Vec position; // Current position of the player
Vec velocity; // Current velocity of the player
// ... Other fields ...
};
// Function to get the next surface time for a player
SurfaceTime GetNextSurfaceTime(const PlayerData& player) {
return CalculateTimeToSurfaces(player.position, player.velocity);
}
// Example usage within your existing GameState processing
GameState ToGameState(rlbot::GameTickPacket& gameTickPacket, int ticksElapsed, int tickSkip, const std::vector<RocketSim::Car*>& rocketSimCars, uint64_t tickCount, const RLGSC::Action& controls) {
GameState gs = {};
const rlbot::flat::Touch* latestTouch = gameTickPacket->ball()->latestTouch();
float currentTime = gameTickPacket->gameInfo()->secondsElapsed();
auto players = gameTickPacket->players();
for (int i = 0; i < players->size(); i++) {
RocketSim::Car* rocketSimCar = (i < rocketSimCars.size()) ? rocketSimCars[i] : nullptr;
PlayerData player = ToPlayer(players->Get(i), rocketSimCar, tickCount, tickSkip, gameTickPacket, controls);
// Calculate time to next surface
SurfaceTime nextSurface = GetNextSurfaceTime(player);
// You can now use nextSurface.time and nextSurface.surface as needed
// For example, store it in PlayerData
// player.nextSurfaceTime = nextSurface.time;
// player.nextSurface = nextSurface.surface;
if (latestTouch != nullptr &&
latestTouch->gameSeconds() > 0 &&
i == latestTouch->playerIndex() &&
currentTime - latestTouch->gameSeconds() < tickSkip / 120.0f) {
player.ballTouchedStep = true;
}
else {
player.ballTouchedStep = false;
}
gs.players.push_back(player);
}
gs.ball = ToPhysObj(gameTickPacket->ball()->physics());
gs.ballInv = gs.ball.Invert();
// ... Existing boost pad processing ...
return gs;
}
// Optional: Function to convert Surface enum to string for debugging
std::string SurfaceToString(Surface surface) {
switch (surface) {
case Surface::SideWall_PosX:
return "SideWall_PosX";
case Surface::SideWall_NegX:
return "SideWall_NegX";
case Surface::BackWall_PosY:
return "BackWall_PosY";
case Surface::BackWall_NegY:
return "BackWall_NegY";
case Surface::Ceiling:
return "Ceiling";
case Surface::Floor:
return "Floor";
default:
return "Unknown";
}
}
Explanation
-
Structs and Enums:
Vec: Represents a 3D vector for position and velocity.
Surface: Enum to identify different surfaces.
SurfaceTime: Holds the time to reach a specific surface and the corresponding Surface enum.
-
Quadratic Solver (SolveQuadratic):
- Solves quadratic equations of the form
a*t^2 + b*t + c = 0.
- Returns real solutions if they exist.
-
Time Calculation (CalculateTimeToSurfaces):
- Side Walls (X-axis):
- Calculates time based on the direction of the velocity.
- Adds the corresponding surface if the time is positive.
- Back Walls (Y-axis):
- Similar approach to side walls.
- Ceiling and Floor (Z-axis):
- Solves the quadratic equation to account for gravity.
- Adds both possible times if they are positive.
-
Determining the Next Surface (GetNextSurfaceTime):
- Invokes
CalculateTimeToSurfaces with the player's current position and velocity.
- Returns the surface with the smallest positive time.
-
Integration with Existing Code:
- In the
ToGameState function, after converting player data, GetNextSurfaceTime is called to determine the next surface the player will reach.
- You can store
nextSurface.time and nextSurface.surface within your PlayerData structure or use them as needed for further game logic.
-
Utility Function (SurfaceToString):
- Converts the
Surface enum to a readable string for debugging purposes.
Usage Example
Here's how you might use the GetNextSurfaceTime function within your game loop or logic:
PlayerData player = /* Obtain player data */;
SurfaceTime nextSurface = GetNextSurfaceTime(player);
if (nextSurface.time < std::numeric_limits<float>::max()) {
std::string surfaceName = SurfaceToString(nextSurface.surface);
std::cout << "Player will reach " << surfaceName << " in " << nextSurface.time << " seconds.\n";
} else {
std::cout << "Player is not moving towards any surface.\n";
}
Considerations
- Accuracy: This calculation assumes constant velocity for the X and Y axes and accounts for constant gravity in the Z-axis. If there are other forces or accelerations (like boost or air control), the calculations would need to be adjusted accordingly.
- Edge Cases:
- No Movement: If the player isn't moving towards a particular axis, the time to reach the corresponding surfaces will be ignored.
- Immediate Surface Contact: If the player is already in contact with a surface and moving away, it won't register as reaching that surface again.
- Performance: The quadratic solver is efficient for real-time calculations, but ensure it's not called excessively in tight loops to maintain performance.
Enhancements
Depending on your application's requirements, you might consider the following enhancements:
- Surface Position Limits: Ensure that the player's extrapolated position doesn't exceed the game's bounds in unexpected ways.
- Collision Detection: Integrate with existing collision detection systems to account for dynamic obstacles or other players.
- Predictive Modelling: Extend the logic to predict multiple future interactions or chain surface contacts.
This implementation should provide a solid foundation for calculating and utilizing the time it takes for a player to reach various surfaces in your Rocket League simulation. Feel free to adapt and expand upon it to fit your specific use case!