> For the complete documentation index, see [llms.txt](https://docs.overdare.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.overdare.com/development/api-reference/classes/simulationball.md).

# SimulationBall

SimulationBall : `PVInstance`

## Overview

Simulation Ball is a Ball object designed to solve the problem of inaccurate synchronization of the physics engine in games. Traditional physics-based balls had issues where each client rendered the ball at different positions due to server latency effects. However, SimulationBall allows all clients to share the same position, velocity, and rotation based on pre-simulated trajectory data.

By using this method, you can obtain the following advantages:

* Latency Compensation: Maintains the same ball movement regardless of server-client latency.
* High Performance: Improves performance by eliminating frame-by-frame physics calculations.
* Predictable Results: Easily query position, velocity, and rotation at a specific point in time based on simulated results.
* Complex Physics Implementation: Enables implementation of non-linear movements based on rotation, such as the Magnus effect.

## Properties

### BallCFrame

`CFrame`

A read-only CFrame representing the actual world position and rotation where the Simulation Ball's collision sphere is currently located. While the `CFrame` property is used as the launch position (input) for starting a new simulation, `BallCFrame` represents the actual position/rotation updated every tick during playback.

> **Note:** This value cannot be set directly.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check the actual position of the collision sphere
print("Collision sphere position:", ball.BallCFrame.Position)
```

### BallMeshCollisionProfile

`string`

Specifies the name of the collision profile applied to the Simulation Ball's mesh component. Setting this value determines how collisions/overlaps with other objects are handled.

> **Note:** This property only affects the actual collision/overlap behavior of the mesh component and does not participate in the trajectory simulation performed by the `Simulate` call.

#### Code Samples

### BallRadius

`number`

Specifies the radius of the ball. It determines the physical collision and rendering size used in the simulation, and is used to match the ball's size with collision detection in the actual game. Larger values can affect the calculation of the ball's mass and air resistance.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")
ball.BallRadius =50
```

### BallState

`Enum.BallState`

Indicates the current state of the Simulation Ball. It can have the following state values:

* `Playing` (1): The simulation is currently playing.
* `Stopped` (2): The simulation is stopped.
* `Paused` (3): The simulation is paused.

This property is read-only, and the state changes via the `Play()`, `Pause()`, and `Stop()` methods.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

if ball.BallState == Enum.BallState.Playing then
    print("The ball is currently playing")
elseif ball.BallState == Enum.BallState.Paused then
    print("The ball is paused")
end
```

### CFrame

`CFrame`

A CFrame representing the starting position and rotation of the Simulation Ball. It can be changed while the ball is not playing.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set the ball's position to (0, 10, 0)
ball.CFrame = CFrame.new(0, 10, 0)

-- Set the ball's position and rotation together
ball.CFrame = CFrame.new(0, 10, 0) * CFrame.Angles(0, math.rad(45), 0)
```

### Color

`Color3`

Specifies the color of the ball. This property only controls the visual representation of the ball and does not affect physical movement.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set the ball to red
ball.Color = Color3.new(1, 0, 0)

-- Set the ball to blue
ball.Color = Color3.fromRGB(0, 100, 255)
```

### EnablePathMarker

`boolean`

Controls the visibility of path markers that visually display the ball's movement trajectory. If set to `true`, the simulated path of the ball is visually displayed, which is useful for debugging or visualization.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Enable path markers
ball.EnablePathMarker = true

-- Disable path markers
ball.EnablePathMarker = false
```

### Material

`Enum.Material`

Specifies the surface material of the ball. Visual representation and physical reactions (friction, restitution, etc.) may vary depending on the material.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set the ball to Plastic material
ball.Material = Enum.Material.Plastic

-- Set the ball to Rubber material
ball.Material = Enum.Material.Rubber
```

### MaterialVariant

`string`

A string specifying a variant of the material. Some materials support multiple variants, and this property allows you to select a specific variant.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set material variant
ball.MaterialVariant = "Smooth"
```

### PathMarkerScale

`number`

Specifies the size scale of the path markers. Larger values make the path markers appear larger. The default value is 0.2.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Display path markers larger
ball.PathMarkerScale = 0.5
```

### PlaybackTime

`number`

A read-only property representing the current playback time of the simulation (in seconds). It is the same as the value returned by the `GetPlaybackTime()` method.

> **Note:** This value is read-only and cannot be assigned directly. To change the playback time, use the `SetPlaybackTime()` method.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check current playback time
print("Current playback time:", ball.PlaybackTime)
```

### Position

`Vector3`

Represents the current world position of the Simulation Ball. This value is the same as the current `CFrame.Position`.

#### Code Samples

### SlomoFactor

`number`

Specifies the multiplier for the simulation playback speed. 1.0 is normal speed, 0.5 is half speed, and 2.0 is double speed. It can be used to implement slow-motion effects or time-lapses.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Play at half speed
ball.SlomoFactor = 0.5

-- Play at double speed
ball.SlomoFactor = 2.0
```

### StaticObjectTypes

`Array`

An array of `Enum.CollisionChannel` values used for collision detection against static objects during the simulation. Collision targets are filtered by object type (ObjectType), and if the array is empty, only the `WorldStatic` channel is targeted by default.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Limit static object collisions to WorldStatic and WorldDynamic
ball.StaticObjectTypes = {Enum.CollisionChannel.WorldStatic, Enum.CollisionChannel.WorldDynamic}
```

### TextureId

`string`

The Asset ID of the texture to apply to the ball's surface. This controls only the visual representation and does not affect physical movement. For example, you can express various styles such as soccer balls, basketballs, etc.

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set texture
ball.TextureId = "ovdrassetid://123456789"
```

### Transparency

`number`

Sets the transparency of the ball. 0 is fully opaque and 1 is fully transparent.

#### Code Samples

## Methods

### ClearPathMarkers

Removes all path markers generated to visualize the simulated trajectory. Useful for resetting existing markers before displaying a new path.

#### Parameters

#### Return

| `void` |   |
| ------ | - |

#### Code Samples

### FindNextBallBounce

Returns information about the next bounce (collision) that will occur after the current playback time (`PlaybackTime`). If there is no bounce or if it is a sliding collision, an empty `BallBounce` object may be returned.

#### Parameters

#### Return

| `BallBounce` | A `BallBounce` object containing information about the next bounce. If there is no bounce, an empty object is returned. |
| ------------ | ----------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Get next bounce information
local nextBounce = ball:FindNextBallBounce()

if nextBounce.BouncedTime > 0 then
    print("Next bounce time:", nextBounce.BouncedTime)
    print("Bounce position:", nextBounce.BouncedPosition)
end
```

### GetAngularVelocityAtTime

Returns the angular velocity (Vector3) of the ball when a specific time (Time) has elapsed since the simulation started. This value represents the rotation direction and speed of the ball, and can be used for the Magnus effect or rotation-based trajectory prediction.

#### Parameters

| `number` Time | Time elapsed since the simulation started (in seconds). Queries the ball's angular velocity at the specified point. |
| ------------- | ------------------------------------------------------------------------------------------------------------------- |

#### Return

| `Vector3` | The angular velocity of the ball at the specified point. Direction represents the axis of rotation, and magnitude represents the angular speed. |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query angular velocity after 2 seconds
local angularVelocity = ball:GetAngularVelocityAtTime(2.0)
print("Angular velocity:", angularVelocity)
print("Rotation speed:", angularVelocity.Magnitude)
```

### GetBallBounceByIndex

Returns bounce information corresponding to the specified index. The index represents the order of bounces that occurred during the simulation, starting from 0. If the index is invalid, an empty `BallBounce` object may be returned.

#### Parameters

| `number` bounceIndex | The index of the bounce to query. Starts from 0 and represents the sequence of bounces that occurred during the simulation. |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------- |

#### Return

| `BallBounce` | A `BallBounce` object containing bounce information for the specified index. |
| ------------ | ---------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Get first bounce information
local firstBounce = ball:GetBallBounceByIndex(0)

if firstBounce.BouncedTime > 0 then
    print("First bounce time:", firstBounce.BouncedTime)
    print("Bounce position:", firstBounce.BouncedPosition)
end
```

### GetBestVelocityToTargetAtTime

Calculates the optimal velocity vector that can reach the target position when the ball is launched toward it at the specified playback time. The return value is a vector combining direction and speed (unit: km/h), and the search takes the Magnus effect caused by spin into account to find a combination that can land within the target radius (`InTargetRadius`). If `UseDesiredPitchAngle` is set to `true`, the search is fixed to the launch pitch angle specified in `InDesiredPitchAngle`; if `false`, the pitch angle is also searched freely.

#### Parameters

| `number` InPlaybackTime        | Simulation playback time. The launch trajectory is calculated based on the ball's position at this point.                                         |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Vector3` InTargetPosition     | Target position.                                                                                                                                  |
| `number` InDesiredSpeed\_Kmh   | Launch speed (in km/h).                                                                                                                           |
| `Vector3` SpinAxis             | Rotation axis vector.                                                                                                                             |
| `number` InSpinSpeed\_RPM      | Rotation speed (in RPM).                                                                                                                          |
| `number` InStepCount           | Number of simulation steps used for the search.                                                                                                   |
| `number` InTargetRadius        | Target radius. It is considered a success if reached within this range.                                                                           |
| `number` InMaxSampleCount      | Maximum number of samples.                                                                                                                        |
| `boolean` UseDesiredPitchAngle | If `true`, the search is fixed to the launch pitch angle specified by `InDesiredPitchAngle`. If `false`, the pitch angle is also searched freely. |
| `number` InDesiredPitchAngle   | The fixed launch pitch angle used when `UseDesiredPitchAngle` is `true`.                                                                          |

#### Return

| `Vector3` | The optimal velocity vector to reach the target position. It contains both direction and speed (in km/h). |
| --------- | --------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")
local targetPosition = Vector3.new(100, 0, 50)

-- Calculate the optimal velocity toward the target at the current playback time
local bestVelocity = ball:GetBestVelocityToTargetAtTime(
    ball.PlaybackTime,
    targetPosition,
    2000,  -- speed (km/h)
    Vector3.new(0, 1, 0),  -- spin axis
    50,  -- spin speed (RPM)
    100,  -- step count
    5,  -- target radius
    100,  -- max sample count
    false,  -- search pitch angle freely
    0  -- unused since UseDesiredPitchAngle is false
)

print("Optimal launch velocity:", bestVelocity)
```

### GetCFrameAtTime

Returns the ball's position and rotation (CFrame) at a specified time (Time) after the simulation starts. This method is useful for obtaining the exact position of the ball at a future or past point in time, and is often used by NPCs or AI to predict the ball's landing spot.

#### Parameters

| `number` Time | Time elapsed since the simulation started (in seconds). Queries the ball's CFrame at the specified point. |
| ------------- | --------------------------------------------------------------------------------------------------------- |

#### Return

| `CFrame` | The CFrame of the ball at the specified point. You can know the position and rotation values. |
| -------- | --------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query ball position and rotation after 3 seconds
local futureCFrame = ball:GetCFrameAtTime(3.0)
print("Position after 3 seconds:", futureCFrame.Position)

-- AI predicts the ball's landing spot
local landingTime = 5.0
local landingCFrame = ball:GetCFrameAtTime(landingTime)
print("Expected landing spot:", landingCFrame.Position)
```

### GetCurrentPlaybackPosition

Returns the ball's position at the current playback time (`PlaybackTime`). This method returns the same result as `GetCFrameAtTime(ball.PlaybackTime).Position`.

#### Parameters

#### Return

| `Vector3` | The ball's position at the current playback time. |
| --------- | ------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check current ball position
local currentPosition = ball:GetCurrentPlaybackPosition()
print("Current ball position:", currentPosition)
```

### GetCurrentSnapshotIndex

Returns the index of the snapshot corresponding to the current playback time (`PlaybackTime`). The snapshot index indicates the position in the snapshot array generated during the simulation.

#### Parameters

#### Return

| `Value` | The index of the snapshot corresponding to the current playback time. |
| ------- | --------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check current snapshot index
local snapshotIndex = ball:GetCurrentSnapshotIndex()
print("Current snapshot index:", snapshotIndex)
```

### GetLinearVelocityAtTime

Returns the linear velocity (Vector3) at a specified time (Time) after the simulation starts. It is used when calculating the ball's movement direction and speed, and is utilized for calculating reflection angles upon collision or visualizing the ball's trajectory.

#### Parameters

| `number` Time | Time elapsed since the simulation started (in seconds). Queries the ball's velocity at the specified point. |
| ------------- | ----------------------------------------------------------------------------------------------------------- |

#### Return

| `Vector3` | The ball's velocity at the specified point. Direction represents the movement direction, and magnitude represents the speed. |
| --------- | ---------------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query velocity after 2 seconds
local velocity = ball:GetLinearVelocityAtTime(2.0)
print("Velocity:", velocity)
print("Speed:", velocity.Magnitude)
```

### GetNextSnapshot

Returns the next `BallSnapshot` in the cached simulation snapshot array based on the current playback time (`PlaybackTime`). It does not take a separate time argument and always operates based on the ball's current playback time. If there is no valid next snapshot, an empty `BallSnapshot` is returned.

#### Parameters

#### Return

| `BallSnapshot` | The snapshot following the current playback time. If there is no valid snapshot, an empty object is returned. |
| -------------- | ------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query the next snapshot
local nextSnapshot = ball:GetNextSnapshot()
print("Next snapshot position:", nextSnapshot.CFrame.Position)
```

### GetPlaybackTime

Returns the current playback time of the simulation. This value indicates how far the simulation has progressed along the trajectory timeline.

#### Parameters

#### Return

| `number` | The current playback time of the simulation (in seconds). |
| -------- | --------------------------------------------------------- |

#### Code Samples

### GetPrevSnapshot

Returns the previous `BallSnapshot` in the cached simulation snapshot array based on the current playback time (`PlaybackTime`). It does not take a separate time argument and always operates based on the ball's current playback time. If there is no valid previous snapshot, an empty `BallSnapshot` is returned.

#### Parameters

#### Return

| `BallSnapshot` | The snapshot preceding the current playback time. If there is no valid snapshot, an empty object is returned. |
| -------------- | ------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query the previous snapshot
local prevSnapshot = ball:GetPrevSnapshot()
print("Previous snapshot position:", prevSnapshot.CFrame.Position)
```

### GetRemainedTimeForNextBounce

Returns the time remaining from the current playback time until the next bounce. If there is no bounce or it is a sliding collision, a very large value (FLT\_MAX) is returned.

#### Parameters

#### Return

| `number` | Time remaining until the next bounce (in seconds). If there is no bounce, a very large value is returned. |
| -------- | --------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check time remaining until next bounce
local remainingTime = ball:GetRemainedTimeForNextBounce()

if remainingTime < math.huge then
    print("Time remaining until next bounce:", remainingTime, "seconds")
else
    print("No next bounce")
end
```

### GetServerWorldTime

Returns the server's current world time in seconds. If a valid game state (`GameState`) exists, it returns the world time synchronized with the server; otherwise, it falls back to the local world time. Used in networked environments where time must be synchronized across multiple clients.

#### Parameters

#### Return

| `number` | The server's current world time (in seconds). |
| -------- | --------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check server world time
print("Server world time:", ball:GetServerWorldTime())
```

### GetSpeedAtTime

Returns the scalar speed at a specified time (Time) after the simulation starts. Unlike `GetLinearVelocityAtTime`, it does not have direction information and simply provides the magnitude of the velocity.

#### Parameters

| `number` Time | Time elapsed since the simulation started (in seconds). Queries the ball's speed at the specified point. |
| ------------- | -------------------------------------------------------------------------------------------------------- |

#### Return

| `number` | The ball's speed at the specified point. |
| -------- | ---------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Query speed after 2 seconds
local speed = ball:GetSpeedAtTime(2.0)
print("Speed after 2 seconds:", speed)
```

### GetStartTime

Returns the time at which the current playback started. This value is recorded based on the server world time when `Play()` is called, and 0 is returned if playback has not started yet.

#### Parameters

#### Return

| `number` | The time at which playback started (server world time, in seconds). Returns 0 if playback has not started yet. |
| -------- | -------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball:Play()

-- Check the server time when playback started
print("Playback start time:", ball:GetStartTime())
```

### IsValidBounceIndex

Checks if the specified index is a valid bounce index. Verifies that the index is within the range of bounces that occurred during the simulation.

#### Parameters

| `number` bounceIndex | The bounce index to check. |
| -------------------- | -------------------------- |

#### Return

| `boolean` | Returns `true` if the index is valid, `false` otherwise. |
| --------- | -------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Check bounce index validity
if ball:IsValidBounceIndex(0) then
    local bounce = ball:GetBallBounceByIndex(0)
    print("First bounce time:", bounce.BouncedTime)
else
    print("Invalid bounce index")
end
```

### Pause

Pauses the currently running simulation. This method can be resumed with `Play()`, and the time paused is not reflected in the simulation. Used when implementing game pauses or slow-motion effects.

#### Parameters

#### Return

| `void` | No return value. |
| ------ | ---------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Play simulation
ball:Play()

-- Pause after 2 seconds
wait(2)
ball:Pause()

-- Resume
wait(1)
ball:Play()
```

### Play

Plays simulation data to actually execute the ball's movement. It is played with the same timing and results on all clients, and it is also possible to resume playback after `Pause()`.

#### Parameters

| `boolean` bReset | Whether to reset the PlaybackTime when playback starts. If omitted, the default value is `false`. |
| ---------------- | ------------------------------------------------------------------------------------------------- |

#### Return

| `void` | No return value. |
| ------ | ---------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Set simulation parameters
local params = BallSimParams.new()
params.InitialCFrame = CFrame.new(0, 10, 0)
params.InitialVelocity = Vector3.new(100, 500, 0)
params.Mass = 0.5

-- Run simulation
ball:Simulate(params)

-- Start playback
ball:Play()
```

### ReSimulateSpinToTargetWithDelay

Performs a resimulation so that the ball heads toward the target position after the specified delay time from the current playback time, using the specified spin axis and spin speed. If `UseDesiredSpeed` is `true`, the speed specified in `InDesiredSpeed` is used as-is and only the direction is calculated; if `false`, both the speed and direction that can reach the target are searched.

#### Parameters

| `number` InDelayTime       | Delay time from the current playback time (in seconds).                                                                             |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Vector3` InTargetPosition | Target position.                                                                                                                    |
| `number` InDesiredSpeed    | Launch speed.                                                                                                                       |
| `Vector3` InSpinAxis       | Rotation axis vector.                                                                                                               |
| `number` InSpinSpeed       | Rotation speed.                                                                                                                     |
| `number` InStepCount       | Number of simulation steps.                                                                                                         |
| `boolean` UseDesiredSpeed  | If `true`, the speed specified by `InDesiredSpeed` is used as-is. If `false`, the speed that can reach the target is also searched. |

#### Return

| `BallSimTargetResult` | The resimulation result. Includes whether a trajectory reaching the target was found (`bHit`), the actual speed (`ActualSpeed`) and direction (`Direction`) used, and the time the target is reached (`HitTime`). |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")
local targetPosition = Vector3.new(100, 0, 50)

-- Resimulate with spin toward the target after 1 second
local result = ball:ReSimulateSpinToTargetWithDelay(
    1.0,  -- after 1 second
    targetPosition,
    2000,  -- speed
    Vector3.new(0, 1, 0),  -- spin axis
    50,  -- spin speed (RPM)
    100,  -- step count
    true  -- use the specified speed as-is
)

if result.bHit then
    print("Hit time:", result.HitTime)
end
```

### ReSimulateToTargetWithDelay

Performs a resimulation so that the ball heads toward the target position after the specified delay time from the current playback time. This method recalculates the trajectory so that the ball heads to the target point at a specific time, and the spin is automatically calculated based on the current angular velocity (if the angular velocity is nearly zero, a minimal spin around an arbitrary axis is applied instead). If `UseDesiredSpeed` is `true`, the speed specified in `InDesiredSpeed` is used as-is and only the direction is calculated; if `false`, both the speed and direction that can reach the target are searched.

#### Parameters

| `number` InDelayTime       | Delay time from the current playback time (in seconds).                                                                             |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Vector3` InTargetPosition | Target position.                                                                                                                    |
| `number` InDesiredSpeed    | Launch speed.                                                                                                                       |
| `number` InStepCount       | Number of simulation steps.                                                                                                         |
| `boolean` UseDesiredSpeed  | If `true`, the speed specified by `InDesiredSpeed` is used as-is. If `false`, the speed that can reach the target is also searched. |

#### Return

| `BallSimTargetResult` | The resimulation result. Includes whether a trajectory reaching the target was found (`bHit`), the actual speed (`ActualSpeed`) and direction (`Direction`) used, and the time the target is reached (`HitTime`). |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")
local targetPosition = Vector3.new(100, 0, 50)

-- Resimulate toward the target after 1 second
local result = ball:ReSimulateToTargetWithDelay(
    1.0,  -- after 1 second
    targetPosition,
    2000,  -- speed
    100,  -- step count
    true  -- use the specified speed as-is
)

if result.bHit then
    print("Hit time:", result.HitTime)
end
```

### ReSimulateWithDelay

Resimulates with the specified direction and velocity after a specified delay time from the current playback time. This method recalculates the ball's trajectory with a new direction and velocity at a specific point in time.

#### Parameters

| `number` InDelayTime  | Delay time from the current playback time (in seconds). |
| --------------------- | ------------------------------------------------------- |
| `Vector3` InDirection | Launch direction vector.                                |
| `number` InSpeed      | Launch speed.                                           |
| `Vector3` InSpinAxis  | Rotation axis vector.                                   |
| `number` InSpinSpeed  | Rotation speed.                                         |
| `number` InStepCount  | Number of simulation steps.                             |

#### Return

| `void` |   |
| ------ | - |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Resimulate with a new direction after 1 second
ball:ReSimulateWithDelay(
    1.0,  -- after 1 second
    Vector3.new(1, 0, 0),  -- direction
    2000,  -- speed
    Vector3.new(0, 1, 0),  -- spin axis
    50,  -- spin speed
    100  -- step count
)
```

### SetPlaybackTime

Changes the simulation's progress time to an arbitrary point. This allows you to rewind to a specific moment or immediately check the state at a future point. For example, calling `SetPlaybackTime(2.5)` sets the simulation to a state where 2.5 seconds have progressed. It can also be changed during Play.

#### Parameters

| `number` InPlaybackTime | Target point in time to move to within the simulation (in seconds). Specify a real number value of 0 or greater, where 0 means the simulation start point. |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |

#### Return

| `void` |   |
| ------ | - |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Run the simulation
ball:Simulate(params)
ball:Play()

-- Move to the 2.5 second mark
ball:SetPlaybackTime(2.5)

-- Check the ball position at that point
local position = ball:GetCurrentPlaybackPosition()
print("Position at 2.5 seconds:", position)
```

### Simulate

Performs the physics simulation of the Simulation Ball and pre-calculates the ball's movement trajectory based on the specified parameters (`BallSimParams`). If `AutoPlay` is `true`, playback starts immediately after the simulation finishes; if `false`, you must call `Play()` separately to start playback.

#### Parameters

| `BallSimParams` InBallSimParams | A physics parameter structure used for the simulation. Contains physical properties such as mass, gravity, initial velocity, spin, damping, and collision characteristics, and the trajectory result varies depending on these values. |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `boolean` AutoPlay              | If `true`, playback starts immediately after the simulation completes. If `false`, playback starts only when `Play()` is called.                                                                                                       |

#### Return

| `void` |   |
| ------ | - |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Create simulation parameters
local params = BallSimParams.new()
params.InitialCFrame = CFrame.new(0, 10, 0)
params.InitialSpeed = 2000
params.InitialDirection = Vector3.new(0, 1, 0)
params.Mass = 0.5
params.InitialSpinAxis = Vector3.new(0, 1, 0)
params.InitialSpinSpeed = 50

-- Run the simulation (start playback separately)
ball:Simulate(params, false)

-- Start playback
ball:Play()
```

### SimulateToTarget

Based on the specified physics parameters (`BallSimParams`), automatically calculates the optimal launch speed and direction that can reach the target position (`InTargetPosition`) and runs the simulation. Unlike `Simulate()`, instead of specifying the initial speed and direction directly, it solves the trajectory backward so that it heads toward the target point. If `UseDesiredSpeed` is `true`, the speed specified in `InBallSimParams` is used as-is and only the direction is calculated; if `false`, both the speed and direction that can reach the target are searched. If `AutoPlay` is `true`, playback starts immediately after the simulation completes; if `false`, playback starts only when `Play()` is called separately.

#### Parameters

| `BallSimParams` InBallSimParams | A physics parameter structure used for the simulation. When `UseDesiredSpeed` is `true`, its `InitialSpeed` value is used as-is as the launch speed. |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Vector3` InTargetPosition      | Target position.                                                                                                                                     |
| `boolean` UseDesiredSpeed       | If `true`, the speed specified in `InBallSimParams` is used as-is. If `false`, the speed that can reach the target is also searched.                 |
| `boolean` AutoPlay              | If `true`, playback starts immediately after the simulation completes. If `false`, playback starts only when `Play()` is called.                     |

#### Return

| `BallSimTargetResult` | The simulation result. Includes whether a trajectory reaching the target was found (`bHit`), the actual speed (`ActualSpeed`) and direction (`Direction`) used, and the time the target is reached (`HitTime`). |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

local params = BallSimParams.new()
params.InitialCFrame = CFrame.new(0, 10, 0)
params.InitialSpeed = 2000
params.Mass = 0.5

local targetPosition = Vector3.new(100, 0, 50)

-- Calculate the velocity toward the target, simulate, and play immediately
local result = ball:SimulateToTarget(params, targetPosition, false, true)

if result.bHit then
    print("Hit time:", result.HitTime)
    print("Actual launch speed:", result.ActualSpeed)
end
```

### Stop

Stops the currently running simulation. Unlike `Pause()`, it aborts playback, and calling `Play()` again will replay from the beginning of the simulation.

#### Parameters

#### Return

| `void` |   |
| ------ | - |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

-- Play the simulation
ball:Play()

-- Stop after 3 seconds
wait(3)
ball:Stop()

-- Replay (from the beginning)
ball:Play()
```

## Events

### Bounded

Event called when the Simulation Ball bounces (collision reflection) off another part. Unlike the `Touched` event, it is called only when a bounce occurs, and sliding collisions are not included.

#### Parameters

\| `BasePart` otherPart | The part that collided with the ball. |

| `BallBounce` bounce | Information at the moment the ball bounces. |
| ------------------- | ------------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.Bounded:Connect(function(otherPart)
    print("Ball bounced with", otherPart.Name)

    -- Get bounce information
    local bounce = ball:FindNextBallBounce()
    print("Bounce position:", bounce.BouncedPosition)
    print("Velocity after bounce:", bounce.BouncedSpeed)
end)
```

### Paused

Event called when the simulation is paused. This event occurs when the `Pause()` method is called.

#### Parameters

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.Paused:Connect(function()
    print("Simulation paused")
end)

ball:Pause()
```

### Played

Event called when the simulation starts playing. This event occurs when the `Play()` method is called.

#### Parameters

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.Played:Connect(function()
    print("Simulation started playing")
end)

ball:Play()
```

### Stopped

Event called when the simulation is stopped. This event occurs when the `Stop()` method is called.

#### Parameters

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.Stopped:Connect(function()
    print("Simulation stopped")
end)

ball:Stop()
```

### Touched

Event called when the Simulation Ball collides with another part. You can use this event to implement collision-based logic such as goal detection, reflection handling, sound playback, etc.

#### Parameters

| `BasePart` otherPart | The part that collided with the ball. |
| -------------------- | ------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.Touched:Connect(function(otherPart)
    print("Ball collided with", otherPart.Name)

    -- Goal detection example
    if otherPart.Name == "Goal" then
        print("Goal!")
    end
end)
```

### TouchEnded

Event called when the Simulation Ball ends contact with another part. Occurs when the ball moves away after colliding with a part.

#### Parameters

| `BasePart` otherPart | The part that the ball had collided with. |
| -------------------- | ----------------------------------------- |

#### Code Samples

```lua
local ball = workspace:FindFirstChild("SimulationBall")

ball.TouchEnded:Connect(function(otherPart)
    print("Ball ended contact with", otherPart.Name)
end)
```

## See also

{% content-ref url="/pages/H8Zx8NxQOhJ15GZAjyMW" %}
[SimulationBall](/manual/studio-manual/object/simulationball.md)
{% endcontent-ref %}
