Improved Sit In Chair Script

local HIT_BOX = script:GetCustomProperty("HitBox"):WaitForObject()
local trigger = script.parent

local isPlayerSitting = false
local curSittingPlayer = nil
local defAnimStance = nil
local keyUsageListener = nil

function OnInteract(trigger,player) 

    if(isPlayerSitting) then
        -- ignore
    else
        player:SetWorldTransform(script:GetWorldTransform())
        defAnimStance = player.animationStance
        --print(defAnimStance)
        player.animationStance = "unarmed_sit_chair_upright"
        player.movementControlMode = MovementControlMode.NONE
        Task.Wait(1)
        trigger.isInteractable = false 
        curSittingPlayer = player
        isPlayerSitting = true
        -- if they press FIRE (left click)
        keyUsageListener = player.bindingPressedEvent:Connect(OnBindingPressed)        
    end

end

-- firing gun (release them)
function OnBindingPressed(player, action)
    if action == "ability_primary" and isPlayerSitting == true then
        keyUsageListener:Disconnect() -- remove mouse listener (fire gun)
        keyUsageListener = nil
        ResetPlayer(curSittingPlayer)
    end
end

function ResetPlayer(player)
    player.animationStance = defAnimStance
    player.movementControlMode = MovementControlMode.VIEW_RELATIVE
    isPlayerSitting = false
    curSittingPlayer = nil
end

function OnEndOverlap(trigger,other)
    if(isPlayerSitting and (other == curSittingPlayer)) then
        ResetPlayer(other)
    end
end

HIT_BOX.interactedEvent:Connect(OnInteract)
HIT_BOX.endOverlapEvent:Connect(OnEndOverlap)

Game.playerLeftEvent:Connect(function(player)

    if curSittingPlayer == nil or player ~= curSittingPlayer then
        return
    end 
    
    isPlayerSitting = false
    curSittingPlayer = nil

end
)


function Tick()
    if isPlayerSitting == false then
        trigger.isInteractable = true
    end
    if curSittingPlayer ~= nil then
        if curSittingPlayer.isJumping then
            ResetPlayer(curSittingPlayer)
        end
    end
end

Latest Posts