Snippets > Collisions/Triggers

Setting the groups the player collides with

Client.OnStart = function()
    -- to set just one collision group:
    Player.CollidesWithGroups = 3
    -- to set multiple collision groups:
    Player.CollidesWithGroups = { 1, 4 }
end

Detecting a collision between the player and an object

Assuming the player's avatar has its default dimensions kPlayerHeight, kPlayerHalfWidth and kPlayerHalfDepth, this checks whether it is colliding with the given shape in the game's world:

Client.OnStart = function()
    kPlayerHeight = 10.5 -- 2.1 map cubes
    kPlayerHalfWidth = 2.0
    kPlayerHalfDepth = 2.0
end

function collides(shape)
    local playerMin = Number3(
        Player.Position.X - kPlayerHalfWidth,
        Player.Position.Y,
        Player.Position.Z - kPlayerHalfDepth)
    local playerMax = Number3(
        Player.Position.X + kPlayerHalfWidth,
        Player.Position.Y + kPlayerHeight,
        Player.Position.Z + kPlayerHalfDepth)
    local halfSize = (
        shape.Width > shape.Depth
        and shape.Width * 0.5
        or shape.Depth * 0.5) * shape.LocalScale.X
    local shapeMin = Number3(
        shape.Position.X - halfSize,
        shape.Position.Y,
        shape.Position.Z - halfSize)
    local shapeMax = Number3(
        shape.Position.X + halfSize,
        shape.Position.Y + shape.Height * shape.LocalScale.X,
        shape.Position.Z + halfSize)
    if playerMax.X > shapeMin.X and
        playerMin.X < shapeMax.X and
        playerMax.Y > shapeMin.Y and
        playerMin.Y < shapeMax.Y and
        playerMax.Z > shapeMin.Z and
        playerMin.Z < shapeMax.Z then
        return true
    end
    return false
end

Basic raycasting (from player)

This code uses the Ray and Impact API objects:

local impact = Player:CastRay()
if impact ~= nil then
    print(impact.Object, impact.Distance)
end