# Raycast

### cast

Performs a basic raycast between two points with collision detection.

```lua
B2Lib.Raycast.cast(startCoords, endCoords, flags, ignoreEntity)
```

**Parameters:**

* `startCoords` (vector3): Starting coordinates for the raycast
* `endCoords` (vector3): Ending coordinates for the raycast
* `flags` (number, optional): Collision flags (default: -1 for all entities)
* `ignoreEntity` (number, optional): Entity handle to ignore during raycast

**Returns:** table - Comprehensive raycast result with hit data

* `hit` (boolean): True if raycast hit something
* `coords` (vector3): Hit coordinates
* `normal` (vector3): Surface normal at hit point
* `entity` (number): Entity handle that was hit
* `distance` (number): Distance to hit point or end
* `flags` (number): Flags used for this raycast
* `timestamp` (number): When this raycast was performed

**Example:**

```lua
local playerPos = GetEntityCoords(PlayerPedId())
local targetPos = vector3(100.0, 200.0, 30.0)
local result = B2Lib.Raycast.cast(playerPos, targetPos)

if result.hit then
    print("Hit something at:", result.coords)
end
```

### fromCamera

Performs a raycast from the camera position in the direction the camera is facing.

```lua
B2Lib.Raycast.fromCamera(maxDistance, ignoreEntity, flags)
```

**Parameters:**

* `maxDistance` (number, optional): Maximum raycast distance
* `ignoreEntity` (number, optional): Entity to ignore during raycast
* `flags` (number, optional): Collision flags (default: -1 for all entities)

**Returns:** table - Raycast result from camera position

**Example:**

```lua
local cameraResult = B2Lib.Raycast.fromCamera(100.0)
if cameraResult.hit then
    print("Camera is looking at:", cameraResult.coords)
end
```

### fromEntity

Performs a raycast from an entity's position in its forward direction.

```lua
B2Lib.Raycast.fromEntity(entity, maxDistance, flags, ignoreEntity)
```

**Parameters:**

* `entity` (number): Entity handle to raycast from
* `maxDistance` (number, optional): Maximum raycast distance
* `flags` (number, optional): Collision flags (default: -1 for all entities)
* `ignoreEntity` (number, optional): Entity to ignore (default: source entity)

**Returns:** table|nil - Raycast result or nil if entity doesn't exist

### downward

Performs a downward raycast for ground detection and surface analysis.

```lua
B2Lib.Raycast.downward(coords, maxDistance, flags)
```

**Parameters:**

* `coords` (vector3, optional): Starting coordinates (default: player position)
* `maxDistance` (number, optional): Maximum downward distance (default: 100.0)
* `flags` (number, optional): Collision flags (default: 1 for world only)

**Returns:** table - Raycast result with ground information

* `hit` (boolean): True if ground was found
* `coords` (vector3): Ground coordinates
* `distance` (number): Distance to ground
* `heightDifference` (number): Height difference from start
* `groundHeight` (number): Ground Z coordinate

### advanced

Performs an advanced raycast with comprehensive options including sphere testing.

```lua
B2Lib.Raycast.advanced(options)
```

**Parameters:**

* `options` (table): Advanced raycast configuration
  * `startCoords` (vector3): Starting coordinates
  * `direction` (vector3): Direction vector
  * `distance` (number): Maximum distance
  * `flags` (number, optional): Collision flags
  * `ignoreEntity` (number, optional): Entity to ignore
  * `radius` (number, optional): Sphere test radius (default: 0.0)

**Returns:** table - Advanced raycast result with additional properties

### cone

Performs multiple raycasts in a cone pattern for area detection.

```lua
B2Lib.Raycast.cone(startCoords, direction, distance, coneAngle, rayCount, flags)
```

**Parameters:**

* `startCoords` (vector3): Starting coordinates
* `direction` (vector3): Direction vector
* `distance` (number): Maximum distance
* `coneAngle` (number, optional): Cone angle in degrees (default: 30)
* `rayCount` (number, optional): Number of rays to cast (default: 5)
* `flags` (number, optional): Collision flags

**Returns:** table - Array of raycast results with ray index and angle

### rotationToDirection

Converts rotation vector to normalized direction vector.

```lua
B2Lib.Raycast.rotationToDirection(rotation)
```

**Parameters:**

* `rotation` (vector3): Rotation vector in degrees

**Returns:** table - Normalized direction vector with x, y, z components

### directionToRotation

Converts direction vector to rotation vector.

```lua
B2Lib.Raycast.directionToRotation(direction)
```

**Parameters:**

* `direction` (vector3): Direction vector

**Returns:** table - Rotation vector in degrees

### hasLineOfSight

Checks if there's a clear line of sight between two points.

```lua
B2Lib.Raycast.hasLineOfSight(startCoords, endCoords, flags, ignoreEntity)
```

**Parameters:**

* `startCoords` (vector3): Starting coordinates
* `endCoords` (vector3): Ending coordinates
* `flags` (number, optional): Collision flags
* `ignoreEntity` (number, optional): Entity to ignore

**Returns:** boolean - True if line of sight is clear

### hasLineOfSightBetweenEntities

Checks if two entities can see each other with eye-level adjustments.

```lua
B2Lib.Raycast.hasLineOfSightBetweenEntities(entity1, entity2, flags)
```

**Parameters:**

* `entity1` (number): First entity handle
* `entity2` (number): Second entity handle
* `flags` (number, optional): Collision flags

**Returns:** boolean - True if entities can see each other

### isInWater

Checks if a position is underwater.

```lua
B2Lib.Raycast.isInWater(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** boolean - True if position is underwater

### getWaterLevel

Gets the water level at specified coordinates.

```lua
B2Lib.Raycast.getWaterLevel(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** number - Water level Z coordinate or -999 if no water

### getWaterInfo

Gets comprehensive water information at specified coordinates.

```lua
B2Lib.Raycast.getWaterInfo(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** table - Water information

* `hasWater` (boolean): True if water exists
* `waterLevel` (number): Water level Z coordinate
* `isUnderwater` (boolean): True if position is underwater
* `depth` (number): Depth below water surface
* `distanceToSurface` (number): Distance to water surface

### forGroundPosition

Gets the ground position below specified coordinates.

```lua
B2Lib.Raycast.forGroundPosition(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** vector3 - Ground position coordinates

### getGroundZ

Gets just the ground Z coordinate below specified coordinates.

```lua
B2Lib.Raycast.getGroundZ(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** number - Ground Z coordinate

### getSurfaceMaterial

Gets the surface material at specified coordinates.

```lua
B2Lib.Raycast.getSurfaceMaterial(coords)
```

**Parameters:**

* `coords` (vector3): Coordinates to check

**Returns:** number|nil - Surface material hash or nil if not found

### forNearestVehicle

Finds the nearest vehicle from camera with detailed vehicle information.

```lua
B2Lib.Raycast.forNearestVehicle(maxDistance)
```

**Parameters:**

* `maxDistance` (number): Maximum search distance

**Returns:** table|nil - Vehicle information or nil if none found

### forNearestPed

Finds the nearest ped from camera with detailed ped information.

```lua
B2Lib.Raycast.forNearestPed(maxDistance)
```

**Parameters:**

* `maxDistance` (number): Maximum search distance

**Returns:** table|nil - Ped information or nil if none found

### forNearestObject

Finds the nearest object from camera with detailed object information.

```lua
B2Lib.Raycast.forNearestObject(maxDistance)
```

**Parameters:**

* `maxDistance` (number): Maximum search distance

**Returns:** table|nil - Object information or nil if none found

### cached

Performs a cached raycast for better performance with repeated operations.

```lua
B2Lib.Raycast.cached(startCoords, endCoords, flags, ignoreEntity)
```

**Parameters:**

* `startCoords` (vector3): Starting coordinates
* `endCoords` (vector3): Ending coordinates
* `flags` (number, optional): Collision flags
* `ignoreEntity` (number, optional): Entity to ignore

**Returns:** table - Cached raycast result

### clearCache

Clears the raycast cache and resets statistics.

```lua
B2Lib.Raycast.clearCache()
```

**Returns:** void

### getCacheStats

Gets cache performance statistics.

```lua
B2Lib.Raycast.getCacheStats()
```

**Returns:** table - Cache statistics

* `hits` (number): Cache hit count
* `misses` (number): Cache miss count
* `totalRequests` (number): Total cache requests
* `hitRate` (number): Cache hit rate percentage
* `cacheSize` (number): Current cache size
* `maxCacheSize` (number): Maximum cache size
* `cacheTimeout` (number): Cache timeout in milliseconds

### updateConfig

Updates raycast system configuration.

```lua
B2Lib.Raycast.updateConfig(newConfig)
```

**Parameters:**

* `newConfig` (table): Configuration options to update

**Returns:** void

### Flags

Raycast collision flags for selective detection:

```lua
local flags = B2Lib.Raycast.Flags

flags.WORLD              -- World geometry (buildings, terrain)
flags.VEHICLES           -- All vehicles
flags.PEDS              -- All pedestrians and players
flags.OBJECTS           -- Props and objects
flags.WATER             -- Water surfaces
flags.FOLIAGE           -- Trees and vegetation
flags.ALL               -- All entity types (-1)
flags.WORLD_AND_VEHICLES -- World + vehicles
flags.WORLD_AND_PEDS    -- World + peds
flags.WORLD_AND_OBJECTS -- World + objects
flags.ENTITIES_ONLY     -- Vehicles + peds + objects
flags.NO_PEDS           -- Everything except peds
```

### Configuration

Configure the raycast system in `config.lua`:

```lua
Config.Raycast = {
    defaultDistance = 100.0,    -- Default maximum distance
    cacheTimeout = 100,         -- Cache timeout in milliseconds
    maxCacheSize = 1000,        -- Maximum cached results
    enableDebug = false,        -- Enable debug logging
    groundDetectionHeight = 100.0, -- Default ground detection height
    waterDetectionEnabled = true   -- Enable water detection
}
```

### Troubleshooting

#### No Hit Detection

1. Check that coordinates are valid and within world bounds
2. Verify collision flags are appropriate for target entities
3. Ensure raycast distance is sufficient
4. Check if ignoreEntity is blocking the raycast

#### Performance Issues

1. Use cached raycasts for repeated operations
2. Reduce raycast distance when possible
3. Use specific collision flags instead of ALL
4. Clear cache periodically to prevent memory buildup

#### Inaccurate Results

1. Verify start and end coordinates are correct
2. Check entity existence before raycasting
3. Use appropriate flags for the detection type
4. Consider using sphere testing for area detection

#### Water Detection Problems

1. Ensure water detection is enabled in configuration
2. Check if coordinates are near water bodies
3. Verify water level calculations are within expected ranges
4. Use appropriate flags that include water surfaces
