Raycast
The Raycast module provides comprehensive raycasting functionality for FiveM resources with advanced collision detection, line-of-sight calculations, and spatial analysis.
cast
Performs a basic raycast between two points with collision detection.
B2Lib.Raycast.cast(startCoords, endCoords, flags, ignoreEntity)
Parameters:
startCoords
(vector3): Starting coordinates for the raycastendCoords
(vector3): Ending coordinates for the raycastflags
(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 somethingcoords
(vector3): Hit coordinatesnormal
(vector3): Surface normal at hit pointentity
(number): Entity handle that was hitdistance
(number): Distance to hit point or endflags
(number): Flags used for this raycasttimestamp
(number): When this raycast was performed
Example:
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.
B2Lib.Raycast.fromCamera(maxDistance, ignoreEntity, flags)
Parameters:
maxDistance
(number, optional): Maximum raycast distanceignoreEntity
(number, optional): Entity to ignore during raycastflags
(number, optional): Collision flags (default: -1 for all entities)
Returns: table - Raycast result from camera position
Example:
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.
B2Lib.Raycast.fromEntity(entity, maxDistance, flags, ignoreEntity)
Parameters:
entity
(number): Entity handle to raycast frommaxDistance
(number, optional): Maximum raycast distanceflags
(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.
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 foundcoords
(vector3): Ground coordinatesdistance
(number): Distance to groundheightDifference
(number): Height difference from startgroundHeight
(number): Ground Z coordinate
advanced
Performs an advanced raycast with comprehensive options including sphere testing.
B2Lib.Raycast.advanced(options)
Parameters:
options
(table): Advanced raycast configurationstartCoords
(vector3): Starting coordinatesdirection
(vector3): Direction vectordistance
(number): Maximum distanceflags
(number, optional): Collision flagsignoreEntity
(number, optional): Entity to ignoreradius
(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.
B2Lib.Raycast.cone(startCoords, direction, distance, coneAngle, rayCount, flags)
Parameters:
startCoords
(vector3): Starting coordinatesdirection
(vector3): Direction vectordistance
(number): Maximum distanceconeAngle
(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.
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.
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.
B2Lib.Raycast.hasLineOfSight(startCoords, endCoords, flags, ignoreEntity)
Parameters:
startCoords
(vector3): Starting coordinatesendCoords
(vector3): Ending coordinatesflags
(number, optional): Collision flagsignoreEntity
(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.
B2Lib.Raycast.hasLineOfSightBetweenEntities(entity1, entity2, flags)
Parameters:
entity1
(number): First entity handleentity2
(number): Second entity handleflags
(number, optional): Collision flags
Returns: boolean - True if entities can see each other
isInWater
Checks if a position is underwater.
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.
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.
B2Lib.Raycast.getWaterInfo(coords)
Parameters:
coords
(vector3): Coordinates to check
Returns: table - Water information
hasWater
(boolean): True if water existswaterLevel
(number): Water level Z coordinateisUnderwater
(boolean): True if position is underwaterdepth
(number): Depth below water surfacedistanceToSurface
(number): Distance to water surface
forGroundPosition
Gets the ground position below specified coordinates.
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.
B2Lib.Raycast.getGroundZ(coords)
Parameters:
coords
(vector3): Coordinates to check
Returns: number - Ground Z coordinate
getSurfaceMaterial
Gets the surface material at specified coordinates.
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.
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.
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.
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.
B2Lib.Raycast.cached(startCoords, endCoords, flags, ignoreEntity)
Parameters:
startCoords
(vector3): Starting coordinatesendCoords
(vector3): Ending coordinatesflags
(number, optional): Collision flagsignoreEntity
(number, optional): Entity to ignore
Returns: table - Cached raycast result
clearCache
Clears the raycast cache and resets statistics.
B2Lib.Raycast.clearCache()
Returns: void
getCacheStats
Gets cache performance statistics.
B2Lib.Raycast.getCacheStats()
Returns: table - Cache statistics
hits
(number): Cache hit countmisses
(number): Cache miss counttotalRequests
(number): Total cache requestshitRate
(number): Cache hit rate percentagecacheSize
(number): Current cache sizemaxCacheSize
(number): Maximum cache sizecacheTimeout
(number): Cache timeout in milliseconds
updateConfig
Updates raycast system configuration.
B2Lib.Raycast.updateConfig(newConfig)
Parameters:
newConfig
(table): Configuration options to update
Returns: void
Flags
Raycast collision flags for selective detection:
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
:
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
Check that coordinates are valid and within world bounds
Verify collision flags are appropriate for target entities
Ensure raycast distance is sufficient
Check if ignoreEntity is blocking the raycast
Performance Issues
Use cached raycasts for repeated operations
Reduce raycast distance when possible
Use specific collision flags instead of ALL
Clear cache periodically to prevent memory buildup
Inaccurate Results
Verify start and end coordinates are correct
Check entity existence before raycasting
Use appropriate flags for the detection type
Consider using sphere testing for area detection
Water Detection Problems
Ensure water detection is enabled in configuration
Check if coordinates are near water bodies
Verify water level calculations are within expected ranges
Use appropriate flags that include water surfaces
Last updated