FS
something is wrong since if im not directly facing a wal it says the car isnt going towars a surface all the time witch is wrong it shouldent matter what way the car is facing only the direction the car is heaing ig
You're absolutely right, and I apologize for the oversight. The issue is that we're not considering the car's actual velocity vector, but rather its forward direction. Let's fix this by using the car's actual velocity for prediction. Here's the corrected version:
} fix the math and logic on this too correctly calculate the landing point of the player too the walls ceiling and florr and kinda hard but the ramps between all the surfaces, the ramps height is 256 witch is the only info you got lol, so do exstrapolation calcualtion to calculate the landing point then render it too rlbot
Understood! Let's tackle the issues step-by-step to ensure accurate collision detection and landing point calculation for your Rocket League bot using RLBot. We'll focus on:
Using the Correct Velocity Vector: Ensuring the car's actual velocity is used rather than its forward direction.
Handling Ramps Properly: Correctly calculating collisions with ramps by considering their incline.
Accurate Landing Point Calculation: Extrapolating the car's trajectory under gravity to find precise collision points.
Rendering the Collision Details in RLBot: Visually representing the collision information for debugging and analysis.
Below is the revised C++ code with detailed explanations to address the mentioned issues.
Revised C++ Code
cpp
#include <vector>
#include <cmath>
#include <limits>
#include <iostream>
#include <utility>
#include "RLBotInterface.h" // Assuming necessary RLBot headers
struct Vec {
float x, y, z;
Vec operator+(const Vec& other) const {
return Vec{ x + other.x, y + other.y, z + other.z };
}
Vec operator-(const Vec& other) const {
return Vec{ x - other.x, y - other.y, z - other.z };
}
Vec operator*(float scalar) const {
return Vec{ x * scalar, y * scalar, z * scalar };
}
float Dot(const Vec& other) const {
return x * other.x + y * other.y + z * other.z;
}
Vec Cross(const Vec& other) const {
return Vec{
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
};
}
Vec Normalized() const {
float mag = std::sqrt(x * x + y * y + z * z);
if (mag == 0) return Vec{0, 0, 0};
return Vec{ x / mag, y / mag, z / mag };
}
};
struct Plane {
Vec normal; // Should be normalized
float d; // Plane equation: normal.dot(P) + d = 0
};
namespace rlbot {
// Placeholder for RLBot's ScopedRenderer and other classes
class ScopedRenderer {
public:
ScopedRenderer(const std::string& name) {
// Initialization code
}
void DrawLine3D(const rlbot::Color& color, const rlbot::flat::Vector3& start, const rlbot::flat::Vector3& end) {
// Drawing logic
}
void DrawRect3D(const rlbot::Color& color, const rlbot::flat::Vector3& position, int width, int height, bool filled, bool bordered) {
// Drawing logic
}
void DrawString3D(const std::string& text, const rlbot::Color& color, const rlbot::flat::Vector3& position, float scale_x, float scale_y) {
// Drawing logic
}
};
struct flat {
struct Vector3 {
float x, y, z;
};
};
struct Color {
int r, g, b, a;
Color(int red, int green, int blue, int alpha) : r(red), g(green), b(blue), a(alpha) {}
};
}
class RLBotBot {
public:
void timewallexsrap(const RLGSC::GameState& gs, int index);
};
void RLBotBot::timewallexsrap(const RLGSC::GameState& gs, int index) {
rlbot::ScopedRenderer renderer("time_to_reach_renderer");
// Field dimensions (assuming Rocket League's standard field size)
const float FIELD_LENGTH = 5120.0f; // Units
const float FIELD_WIDTH = 4096.0f;
const float FIELD_HEIGHT = 2044.0f;
const float RAMP_HEIGHT = 256.0f; // Given
const float MIN_VELOCITY_THRESHOLD = 1.0f;
// Gravity (Rocket League's gravity)
const Vec gravity(0.0f, 0.0f, -650.0f);
// Thresholds for surface detection
const float SURFACE_DISTANCE_THRESHOLD = 5.0f;
const float SURFACE_ANGLE_THRESHOLD = 0.1f; // Radians
// Validate player index
if (index >= gs.players.size()) {
std::cerr << "Invalid player index: " << index << std::endl;
return;
}
const auto& car = gs.players[index];
Vec carPos = car.phys.pos;
Vec carVel = car.phys.vel; // Using actual velocity
Vec carUp = car.phys.rotMat.up;
// Early exit if velocity is below threshold
if (std::sqrt(carVel.x * carVel.x + carVel.y * carVel.y + carVel.z * carVel.z) < MIN_VELOCITY_THRESHOLD) {
std::cout << "Car velocity below threshold." << std::endl;
return;
}
// Define all planes (walls, floor, ceiling, ramps)
std::vector<Plane> planes;
// Floor and Ceiling
planes.push_back(Plane{ Vec{0, 0, 1}, 0 }); // Floor: z = 0
planes.push_back(Plane{ Vec{0, 0, -1}, FIELD_HEIGHT }); // Ceiling: z = FIELD_HEIGHT
// Left and Right Walls
planes.push_back(Plane{ Vec{1, 0, 0}, FIELD_WIDTH }); // Right Wall: x = FIELD_WIDTH
planes.push_back(Plane{ Vec{-1, 0, 0}, FIELD_WIDTH }); // Left Wall: x = -FIELD_WIDTH
// Back and Front Walls
planes.push_back(Plane{ Vec{0, 1, 0}, FIELD_LENGTH }); // Back Wall: y = FIELD_LENGTH
planes.push_back(Plane{ Vec{0, -1, 0}, FIELD_LENGTH }); // Front Wall: y = -FIELD_LENGTH
// Ramps
// Side Ramp: Inclined towards positive X
float sideRampAngle = std::atan2(RAMP_HEIGHT, FIELD_WIDTH);
planes.push_back(Plane{ Vec{std::cos(sideRampAngle), 0.0f, std::sin(sideRampAngle)}, 0 });
// Front Ramp
float frontRampAngle = std::atan2(RAMP_HEIGHT, FIELD_LENGTH);
planes.push_back(Plane{ Vec{0.0f, std::cos(frontRampAngle), std::sin(frontRampAngle)}, 0 });
// Additional ramps can be added similarly by adjusting normals and offsets
// Function to check collision with a plane
auto checkCollision = [&](const Vec& pos, const Vec& vel, const Vec& acc, const Plane& plane) -> std::pair<float, Vec> {
// Plane equation: normal.dot(P) + d = 0
// Position as a function of time: P(t) = pos + vel * t + 0.5 * acc * t^2
// Substitute into plane equation:
// normal.dot(pos) + d + normal.dot(vel) * t + 0.5 * normal.dot(acc) * t^2 = 0
float a = 0.5f * plane.normal.Dot(acc);
float b = plane.normal.Dot(vel);
float c = plane.normal.Dot(pos) + plane.d;
// Solve quadratic equation: a*t^2 + b*t + c = 0
float discriminant = b * b - 4 * a * c;
if (discriminant < 0 || a == 0) {
// No real solution or not a quadratic equation
return { std::numeric_limits<float>::infinity(), Vec{0, 0, 0} };
}
float sqrt_disc = std::sqrt(discriminant);
float t1 = (-b + sqrt_disc) / (2 * a);
float t2 = (-b - sqrt_disc) / (2 * a);
// We need the smallest positive t
float t = std::numeric_limits<float>::infinity();
if (t1 > 0 && t1 < t) t = t1;
if (t2 > 0 && t2 < t) t = t2;
if (t == std::numeric_limits<float>::infinity()) {
// No valid positive time solution
return { t, Vec{0, 0, 0} };
}
// Calculate collision position
Vec collisionPos = pos + vel * t + acc * (0.5f * t * t);
return { t, collisionPos };
};
float earliestTime = std::numeric_limits<float>::infinity();
Vec collisionPoint;
Vec collisionNormal;
bool isCurrentlyOnSurface = false;
// Iterate through all planes to find the earliest collision
for (const auto& plane : planes) {
auto [time, point] = checkCollision(carPos, carVel, gravity, plane);
// Check if the car is already on the surface
float distanceToPlane = std::abs(plane.normal.Dot(carPos) + plane.d);
float alignment = std::abs(carUp.Dot(plane.normal));
if (distanceToPlane < SURFACE_DISTANCE_THRESHOLD && alignment > (1 - SURFACE_ANGLE_THRESHOLD)) {
isCurrentlyOnSurface = true;
collisionPoint = carPos;
collisionNormal = plane.normal;
break;
}
// Update earliest collision
if (time < earliestTime) {
// Validate collision point is within field bounds
bool withinBounds = true;
if (plane.normal.x != 0) {
float x = plane.normal.x > 0 ? FIELD_WIDTH : -FIELD_WIDTH;
if (!(x - 1000.0f < point.x && point.x < x + 1000.0f)) { // 1000 units margin
withinBounds = false;
}
}
if (plane.normal.y != 0) {
float y = plane.normal.y > 0 ? FIELD_LENGTH : -FIELD_LENGTH;
if (!(y - 1000.0f < point.y && point.y < y + 1000.0f)) {
withinBounds = false;
}
}
if (point.z < 0 || point.z > FIELD_HEIGHT) {
withinBounds = false;
}
if (withinBounds) {
earliestTime = time;
collisionPoint = point;
collisionNormal = plane.normal;
}
}
}
// Render results
if (isCurrentlyOnSurface) {
std::cout << "Car is currently on a surface." << std::endl;
}
else if (earliestTime == std::numeric_limits<float>::infinity()) {
std::cout << "Car is not moving towards any surface." << std::endl;
return;
}
else {
std::cout << "Time to collision: " << earliestTime << " seconds." << std::endl;
}
// Convert collision position to RLBot's Vector3
rlbot::flat::Vector3 rl_collisionPos = { collisionPoint.x, collisionPoint.y, collisionPoint.z };
rlbot::flat::Vector3 rl_carPos = { carPos.x, carPos.y, carPos.z };
// Draw trajectory line
rlbot::Color lineColor(255, 255, 0, 255); // Yellow
renderer.DrawLine3D(lineColor, rl_carPos, rl_collisionPos);
// Draw collision point marker
rlbot::Color markerColor(255, 0, 0, 255); // Red
float markerSize = 50.0f;
renderer.DrawRect3D(markerColor, rl_collisionPos, static_cast<int>(markerSize), static_cast<int>(markerSize), true, true);
// Display collision information
rlbot::Color textColor(255, 255, 255, 255); // White
std::string surfaceInfo = isCurrentlyOnSurface ?
"On surface" :
"Time to collision: " + std::to_string(earliestTime) + "s";
rlbot::flat::Vector3 textPosition = { carPos.x, carPos.y + 100.0f, carPos.z };
renderer.DrawString3D(surfaceInfo, textColor, textPosition, 1.0f, 1.0f);
// Draw normal vector at collision point
rlbot::flat::Vector3 normalEnd = {
collisionPoint.x + collisionNormal.x * 100.0f,
collisionPoint.y + collisionNormal.y * 100.0f,
collisionPoint.z + collisionNormal.z * 100.0f
};
rlbot::flat::Vector3 rl_normalEnd = { normalEnd.x, normalEnd.y, normalEnd.z };
rlbot::Color normalColor(0, 255, 0, 255); // Green
renderer.DrawLine3D(normalColor, rl_collisionPos, rl_normalEnd);
}
Detailed Explanation
Structs and Helper Functions:
Vec Struct: Represents a 3D vector with essential operations like addition, subtraction, scalar multiplication, dot product, cross product, and normalization.
Plane Struct: Represents a plane using its normal vector and the plane equation constant d.
Renderer and Color Classes:
ScopedRenderer: Placeholder for RLBot's renderer to draw lines, rectangles, and text in the game.
Color Class: Represents RGBA colors for rendering.
Function Breakdown:
Velocity Check: Before performing any collision calculations, the car's velocity magnitude is checked against a minimum threshold to avoid unnecessary computations when the car is nearly stationary.
Plane Definitions:
Floor and Ceiling: Defined using upward and downward normals.
Walls (Left, Right, Front, Back): Defined based on standard Rocket League field dimensions.
Ramps:
Side Ramp: Inclined plane towards the positive X-axis.
Front Ramp: Inclined plane towards the positive Y-axis.
Note: Adjust ramp normals and plane constants based on actual ramp orientations in the game.
Collision Detection (checkCollision Lambda):
Equation: Solves the quadratic equation derived from substituting the car's trajectory into the plane equation.
Discriminant Check: Ensures real solutions exist.
Time (t) Selection: Chooses the smallest positive time from the solutions.
Collision Position Calculation: Computes the exact position where the collision occurs.
Collision Iteration:
Iterates through all defined planes to find the earliest collision time and corresponding collision point.
On-Surface Check: Determines if the car is already on a surface based on distance and angle thresholds.
Boundary Validation: Ensures the collision point lies within the field boundaries with a reasonable margin.
Testing and Validation
To ensure the revised code functions as expected:
Unit Testing:
Vector Operations: Validate all Vec operations with known inputs and outputs.
Collision Calculations: Test checkCollision with various positions, velocities, and planes to ensure accurate time and position outputs.
In-Game Testing:
Visual Verification: Use the rendered lines, markers, and text to verify collision points and normals align with actual in-game surfaces.
Edge Cases: Test scenarios where the car approaches ramps, walls at angles, and when the car is stationary or moving parallel to surfaces.
Performance Monitoring:
Ensure that the collision detection and rendering do not introduce noticeable lag or performance drops in the game.
Further Enhancements
Dynamic Ramp Handling:
Multiple Ramp Orientations: Extend the plane definitions to accommodate ramps facing different directions.
Slope Variations: Handle ramps with varying inclines by parameterizing ramp angles.
Collision Filtering:
Surface Types: Differentiate between various surfaces (e.g., soft wall, hard wall, ramp) to apply specific behaviors upon collision.
Event Triggers: Implement callbacks or event triggers when specific collision conditions are met.
Predictive Modeling:
Time Steps: Instead of relying solely on analytical solutions, incorporate discrete time steps to simulate the car's trajectory for more complex collision scenarios.
Advanced Physics: Consider factors like air resistance or boost usage that can alter the car's velocity and trajectory.
Optimization:
Caching Plane Data: If plane configurations are static, cache certain computations to reduce processing overhead.
Parallel Processing: Utilize multi-threading for collision checks if dealing with multiple cars or complex environments.
By implementing the above revisions and recommendations, your RLBot should accurately detect collisions with various surfaces, including ramps, and provide precise landing point calculations. This enhanced collision detection will significantly improve your bot's decision-making and overall performance in the game.
Not yet included in a published release.
Rendering:
Trajectory Line: Draws a yellow line from the car's current position to the collision point.
Collision Marker: Draws a red rectangle at the collision point.
Collision Info: Displays text indicating whether the car is on a surface or the time to collision.
Normal Vector: Draws a green line representing the plane's normal at the collision point for visual understanding.
Handling Ramps:
Ramp Normals: Calculated using trigonometric functions based on the ramp height and width to determine the incline angle.
Plane Offsets (d): Set to 0 assuming ramps start at the origin; adjust if ramps are placed elsewhere.
Normalization: Ensures all normals are unit vectors for accurate calculations.
Assumptions and Notes:
Field Dimensions: Standard Rocket League field dimensions are used. Adjust FIELD_LENGTH, FIELD_WIDTH, and FIELD_HEIGHT if your environment differs.
Ramp Placement: The current setup assumes ramps are aligned with the field axes. If ramps are positioned differently, adjust the normals and offsets accordingly.
Rendering Limits: RLBot has limitations on drawing distances and frequencies. Ensure rendering calls are optimized to avoid performance issues.
Gravity: Set to Rocket League's standard gravity. Modify if your game settings differ.