Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

class GoalDetector { public: // Use the RocketSim Team type for consistency using Team =…

  1. User

    class GoalDetector { public: // Use the RocketSim Team type for consistency using Team = RocketSim::Team;

    // Constructor
    GoalDetector() {}
    
    /**
     * @brief Resets the internal previous game state
     * @param initialState The initial state to set as the previous state
     */
    void Reset(const GameState& initialState) {
        previousState = initialState;
    }
    
    /**
     * @brief Determines if the latest goal was caused by a player or by random state changes.
     *
     * @param currentState The current game state after the latest update.
     * @return true if the goal was caused by a player, false otherwise.
     */
    bool WasGoalScoredByPlayer(const GameState& currentState) {
        Team scoringTeam;
    
        // Step 1: Detect if a goal has been scored by comparing score lines
        bool goalScored = false;
    
        if (currentState.scoreLine[0] > previousState.scoreLine[0]) {
            goalScored = true;
            scoringTeam = Team::BLUE;
        }
        else if (currentState.scoreLine[1] > previousState.scoreLine[1]) {
            goalScored = true;
            scoringTeam = Team::ORANGE;
        }
    
        if (!goalScored) {
            // No goal scored in this update
            previousState = currentState;  // Update previousState
            return false;
        }
    
        // Step 2: Check if any player on the scoring team touched the ball before the goal
        bool playerTouched = false;
        for (const auto& player : currentState.players) {
            if (player.team != scoringTeam) {
                continue; // Only consider players on the scoring team
            }
    
            if (player.ballTouchedStep || player.ballTouchedTick) {
                playerTouched = true;
                break;
            }
        }
    
        if (playerTouched) {
            previousState = currentState;  // Update previousState
            return true; // Goal was caused by a player
        }
    
        // Step 3: Alternatively, check if lastTouchCarID corresponds to a player on the scoring team
        int lastTouchID = currentState.lastTouchCarID;
        if (lastTouchID != -1) {
            for (const auto& player : currentState.players) {
                if (player.carId == static_cast<uint32_t>(lastTouchID) && player.team == scoringTeam) {
                    previousState = currentState;  // Update previousState
                    return true; // Goal was caused by a player
                }
            }
        }
    
        // If no player on the scoring team touched the ball, attribute to random
        previousState = currentState;  // Update previousState
        return false;
    }
    

    private: GameState previousState; // Store the previous state of the game };

    static GoalDetector goalDetector;

    rlbot::Controller RLBotBot::GetOutput(rlbot::GameTickPacket gameTickPacket) { float curTime = gameTickPacket->gameInfo()->secondsElapsed(); float deltaTime = curTime - prevTime; prevTime = curTime; int ticksElapsed = roundf(deltaTime * 120); ticks += ticksElapsed;

    std::vector<RocketSim::Car*> rocketSimCars;
    if (predictionArena != nullptr) {
        auto cars = predictionArena->GetCars();
        rocketSimCars.assign(cars.begin(), cars.end());
    }
    
    GameState gs = ToGameState(gameTickPacket, ticksElapsed, params.tickSkip, rocketSimCars, ticks, controls);
    auto& localPlayer = gs.players[index];
    
    // Initial goal detector setup
    if (ticks == 0) {
        // Reset the goal detector with the initial state
        goalDetector.Reset(gs);
    }
    
    // Goal detection logic
    bool goalByPlayer = goalDetector.WasGoalScoredByPlayer(gs);
    if (goalByPlayer) {
        std::cout << "Goal was scored by a player!" << std::endl;
    }
    else {
        std::cout << "Goal was random!" << std::endl;
    }
    
    ListenAndPrintKeys();
    
    //ResetToDefaultKickoff();  // Call the reset function
    
    //RenderBallInfo(gs);
    
    //RenderCarInfo(gs);
    
    if (renderRewardEnabled) {
        RenderReward(gs);
    }
    if (renderCarStateTableEnabled) {
        //RenderCarStateTable(gs);
        //RenderCarStateTable(gs);
    }
    if (renderBallPredictionsEnabled) {
        //RenderBallPredictions(gs);
    }
    if (updatePredictionArenaEnabled) {
        UpdatePredictionArena(gs);
    }
    if (renderTimeToReachBallEnabled) {
        //RenderTimeToReachBall(gs);
    }
    gs.lastArena = predictionArena;
    
    if (g_RLBotParams.userInputMode) {
        controls = ConvertToAction(g_RLBotParams.userControls);
    }
    else {
        if (updateAction) {
            updateAction = false;
            action = policyInferUnit->InferPolicySingle(localPlayer, gs, controls, true);
        }
        if (ticks >= params.tickSkip || ticks == -1) {
            controls = action;
            ticks = 0;
            updateAction = true;
        }
    }
    
    auto rc = rlbot::Controller();
    rc.throttle = controls.throttle;
    rc.steer = controls.steer;
    rc.pitch = controls.pitch;
    rc.yaw = controls.yaw;
    rc.roll = controls.roll;
    rc.boost = controls.boost;
    rc.jump = controls.jump;
    rc.handbrake = controls.handbrake;
    
    return rc;
    

    } make that the goal scored gets activated if the ball is within 100 distance from the goal

  2. Assistant

    To enhance your GoalDetector by activating a goal when the ball is within 100 units of the goal, you'll need to incorporate a distance check into your existing goal detection logic. This ensures that a goal is only recognized if both the score has changed and the ball is sufficiently close to the goal. Here's a step-by-step guide to implementing this feature:

    1. Define Goal Positions

    First, you need to specify the exact positions of both goals on the field. Assuming a standard Rocket League field orientation, where the blue goal is on the positive Y-axis and the orange goal is on the negative Y-axis, you can define them as follows:

    // Define goal positions based on Rocket League's field dimensions
    const Vector3 BLUE_GOAL_POSITION = Vector3{ 0.0f, 5120.0f, 0.0f };   // Example coordinates
    const Vector3 ORANGE_GOAL_POSITION = Vector3{ 0.0f, -5120.0f, 0.0f };
    

    Adjust the Y-values (5120.0f and -5120.0f) based on the actual field dimensions used in your project.

    2. Update the GameState Structure

    Ensure that your GameState structure includes the ball's current position. This is crucial for calculating the distance between the ball and the goal.

    struct GameState {
        // ... existing members ...
        Vector3 ballPosition;  // Add this line to store the ball's position
        // ...
    };
    

    3. Implement a Distance Calculation Function

    Create a helper function to calculate the Euclidean distance between two points in 3D space:

    #include <cmath>  // Include for sqrt and pow
    
    // Utility function to compute Euclidean distance between two points
    float ComputeDistance(const Vector3& a, const Vector3& b) {
        float dx = a.x - b.x;
        float dy = a.y - b.y;
        float dz = a.z - b.z;
        return std::sqrt(dx * dx + dy * dy + dz * dz);
    }
    

    4. Modify the WasGoalScoredByPlayer Method

    Incorporate the distance check into your goal detection logic. The method will now verify both the score change and the ball's proximity to the goal.

    bool WasGoalScoredByPlayer(const GameState& currentState) {
        Team scoringTeam;
    
        // Step 1: Detect if a goal has been scored by comparing score lines
        bool goalScored = false;
    
        if (currentState.scoreLine[0] > previousState.scoreLine[0]) {
            goalScored = true;
            scoringTeam = Team::BLUE;
        }
        else if (currentState.scoreLine[1] > previousState.scoreLine[1]) {
            goalScored = true;
            scoringTeam = Team::ORANGE;
        }
    
        if (!goalScored) {
            // No goal scored in this update
            previousState = currentState;  // Update previousState
            return false;
        }
    
        // Step 2: Check if the ball is within 100 units of the scoring team's goal
        Vector3 goalPosition;
        if (scoringTeam == Team::BLUE) {
            goalPosition = BLUE_GOAL_POSITION;
        }
        else {
            goalPosition = ORANGE_GOAL_POSITION;
        }
    
        float distance = ComputeDistance(currentState.ballPosition, goalPosition);
        if (distance > 100.0f) {
            // Ball is not sufficiently close to the goal; ignore the goal
            previousState = currentState;  // Update previousState
            return false;
        }
    
        // Step 3: Check if any player on the scoring team touched the ball before the goal
        bool playerTouched = false;
        for (const auto& player : currentState.players) {
            if (player.team != scoringTeam) {
                continue; // Only consider players on the scoring team
            }
    
            if (player.ballTouchedStep || player.ballTouchedTick) {
                playerTouched = true;
                break;
            }
        }
    
        if (playerTouched) {
            previousState = currentState;  // Update previousState
            return true; // Goal was caused by a player
        }
    
        // Step 4: Alternatively, check if lastTouchCarID corresponds to a player on the scoring team
        int lastTouchID = currentState.lastTouchCarID;
        if (lastTouchID != -1) {
            for (const auto& player : currentState.players) {
                if (player.carId == static_cast<uint32_t>(lastTouchID) && player.team == scoringTeam) {
                    previousState = currentState;  // Update previousState
                    return true; // Goal was caused by a player
                }
            }
        }
    
        // If no player on the scoring team touched the ball, attribute to random
        previousState = currentState;  // Update previousState
        return false;
    }
    

    5. Populate ballPosition in ToGameState

    Ensure that the ballPosition is correctly populated within your ToGameState function based on the gameTickPacket. Here's an example of how you might do this:

    GameState ToGameState(const rlbot::GameTickPacket* gameTickPacket, int ticksElapsed, int tickSkip, const std::vector<RocketSim::Car*>& rocketSimCars, int ticks, Controls& controls) {
        GameState gs;
        
        // Populate ball position
        gs.ballPosition = Vector3{
            gameTickPacket->physics().ball().physics().location().x(),
            gameTickPacket->physics().ball().physics().location().y(),
            gameTickPacket->physics().ball().physics().location().z()
        };
    
        // ... populate other GameState members ...
    
        return gs;
    }
    

    Ensure that the Vector3 constructor and accessing methods (x(), y(), z()) align with your actual data structures.

    6. Verify and Adjust Goal Positions

    Make sure that the BLUE_GOAL_POSITION and ORANGE_GOAL_POSITION accurately reflect the in-game positions of the goals. If Rocket League's coordinate system places goals differently, adjust the X, Y, and Z values accordingly.

    For example, in Rocket League's standard coordinate system:

    • The Blue goal is typically at (0, 5120, 0)
    • The Orange goal is at (0, -5120, 0)

    However, always confirm with your game's specific coordinate system.

    7. Complete Updated GoalDetector Class

    Here's the complete updated GoalDetector class incorporating all the changes:

    #include <cmath>
    #include <vector>
    #include <iostream>
    
    // Assuming Vector3 is defined as follows
    struct Vector3 {
        float x;
        float y;
        float z;
    };
    
    // Utility function to compute Euclidean distance between two points
    float ComputeDistance(const Vector3& a, const Vector3& b) {
        float dx = a.x - b.x;
        float dy = a.y - b.y;
        float dz = a.z - b.z;
        return std::sqrt(dx * dx + dy * dy + dz * dz);
    }
    
    class GoalDetector {
    public:
        // Use the RocketSim Team type for consistency
        using Team = RocketSim::Team;
    
        // Constructor
        GoalDetector() {}
    
        /**
         * @brief Resets the internal previous game state
         * @param initialState The initial state to set as the previous state
         */
        void Reset(const GameState& initialState) {
            previousState = initialState;
        }
    
        /**
         * @brief Determines if the latest goal was caused by a player or by random state changes.
         *
         * @param currentState The current game state after the latest update.
         * @return true if the goal was caused by a player, false otherwise.
         */
        bool WasGoalScoredByPlayer(const GameState& currentState) {
            Team scoringTeam;
    
            // Step 1: Detect if a goal has been scored by comparing score lines
            bool goalScored = false;
    
            if (currentState.scoreLine[0] > previousState.scoreLine[0]) {
                goalScored = true;
                scoringTeam = Team::BLUE;
            }
            else if (currentState.scoreLine[1] > previousState.scoreLine[1]) {
                goalScored = true;
                scoringTeam = Team::ORANGE;
            }
    
            if (!goalScored) {
                // No goal scored in this update
                previousState = currentState;  // Update previousState
                return false;
            }
    
            // Step 2: Check if the ball is within 100 units of the scoring team's goal
            Vector3 goalPosition;
            if (scoringTeam == Team::BLUE) {
                goalPosition = BLUE_GOAL_POSITION;
            }
            else {
                goalPosition = ORANGE_GOAL_POSITION;
            }
    
            float distance = ComputeDistance(currentState.ballPosition, goalPosition);
            if (distance > 100.0f) {
                // Ball is not sufficiently close to the goal; ignore the goal
                previousState = currentState;  // Update previousState
                return false;
            }
    
            // Step 3: Check if any player on the scoring team touched the ball before the goal
            bool playerTouched = false;
            for (const auto& player : currentState.players) {
                if (player.team != scoringTeam) {
                    continue; // Only consider players on the scoring team
                }
    
                if (player.ballTouchedStep || player.ballTouchedTick) {
                    playerTouched = true;
                    break;
                }
            }
    
            if (playerTouched) {
                previousState = currentState;  // Update previousState
                return true; // Goal was caused by a player
            }
    
            // Step 4: Alternatively, check if lastTouchCarID corresponds to a player on the scoring team
            int lastTouchID = currentState.lastTouchCarID;
            if (lastTouchID != -1) {
                for (const auto& player : currentState.players) {
                    if (player.carId == static_cast<uint32_t>(lastTouchID) && player.team == scoringTeam) {
                        previousState = currentState;  // Update previousState
                        return true; // Goal was caused by a player
                    }
                }
            }
    
            // If no player on the scoring team touched the ball, attribute to random
            previousState = currentState;  // Update previousState
            return false;
        }
    
    private:
        GameState previousState;  // Store the previous state of the game
    
        // Define goal positions, adjust coordinates based on actual field dimensions
        const Vector3 BLUE_GOAL_POSITION = Vector3{ 0.0f, 5120.0f, 0.0f };   // Example coordinates
        const Vector3 ORANGE_GOAL_POSITION = Vector3{ 0.0f, -5120.0f, 0.0f };
    };
    
    static GoalDetector goalDetector;
    

    8. Integrate with RLBotBot::GetOutput

    Ensure that the ballPosition is correctly set in each game tick and that the GoalDetector is used appropriately. Here's how your GetOutput method should look with the updated goal detection:

    rlbot::Controller RLBotBot::GetOutput(rlbot::GameTickPacket gameTickPacket) {
        float curTime = gameTickPacket->gameInfo()->secondsElapsed();
        float deltaTime = curTime - prevTime;
        prevTime = curTime;
        int ticksElapsed = roundf(deltaTime * 120);
        ticks += ticksElapsed;
    
        std::vector<RocketSim::Car*> rocketSimCars;
        if (predictionArena != nullptr) {
            auto cars = predictionArena->GetCars();
            rocketSimCars.assign(cars.begin(), cars.end());
        }
    
        GameState gs = ToGameState(gameTickPacket, ticksElapsed, params.tickSkip, rocketSimCars, ticks, controls);
        auto& localPlayer = gs.players[index];
    
        // Initial goal detector setup
        if (ticks == 0) {
            // Reset the goal detector with the initial state
            goalDetector.Reset(gs);
        }
    
        // Goal detection logic
        bool goalByPlayer = goalDetector.WasGoalScoredByPlayer(gs);
        if (goalByPlayer) {
            std::cout << "Goal was scored by a player!" << std::endl;
        }
        else {
            std::cout << "Goal was random!" << std::endl;
        }
    
        ListenAndPrintKeys();
    
        //ResetToDefaultKickoff();  // Call the reset function
    
        //RenderBallInfo(gs);
    
        //RenderCarInfo(gs);
    
        if (renderRewardEnabled) {
            RenderReward(gs);
        }
        if (renderCarStateTableEnabled) {
            //RenderCarStateTable(gs);
            //RenderCarStateTable(gs);
        }
        if (renderBallPredictionsEnabled) {
            //RenderBallPredictions(gs);
        }
        if (updatePredictionArenaEnabled) {
            UpdatePredictionArena(gs);
        }
        if (renderTimeToReachBallEnabled) {
            //RenderTimeToReachBall(gs);
        }
        gs.lastArena = predictionArena;
    
        if (g_RLBotParams.userInputMode) {
            controls = ConvertToAction(g_RLBotParams.userControls);
        }
        else {
            if (updateAction) {
                updateAction = false;
                action = policyInferUnit->InferPolicySingle(localPlayer, gs, controls, true);
            }
            if (ticks >= params.tickSkip || ticks == -1) {
                controls = action;
                ticks = 0;
                updateAction = true;
            }
        }
    
        rlbot::Controller rc;
        rc.throttle = controls.throttle;
        rc.steer = controls.steer;
        rc.pitch = controls.pitch;
        rc.yaw = controls.yaw;
        rc.roll = controls.roll;
        rc.boost = controls.boost;
        rc.jump = controls.jump;
        rc.handbrake = controls.handbrake;
    
        return rc;
    }
    

    9. Testing

    After implementing these changes:

    1. Compile and Run: Ensure there are no compilation errors and the program runs as expected.
    2. Simulate Goals: Test scenarios where goals are scored both by players and via random state changes to verify the accuracy of detection.
    3. Adjust Distance if Needed: If you find that the 100-unit threshold is too restrictive or lenient, adjust it accordingly based on in-game observations.

    Summary

    By integrating a distance check into your goal detection logic, you ensure that goals are only recognized when the ball is both scoring (as indicated by a score change) and physically near the goal area. This reduces false positives caused by score changes that aren't actual goals or by ball movements unrelated to scoring.

    Feel free to adjust the goal positions and distance threshold (100.0f) based on the specific requirements and observations from your game environment.