I was working on a collisions script where if a player has a keycard in their hand, they can go through a door, but if not, they can’t go through. However, the collisions are not working and any player can go through regardless of whether they have a keycard or not. What am I doing wrong?
Script:
local physicsService = game:GetService("PhysicsService")
local playersID = "Players"
local barrierID = "Barriers"
physicsService:CreateCollisionGroup(playersID)
physicsService:CreateCollisionGroup(barrierID)
physicsService:CollisionGroupSetCollidable(playersID, barrierID, true)
function onPlayerAdded(player)
addToCollisionGroup(player, playersID)
if player.Character then addToCollisionGroup(player, playersID) end
end
function setCollision(obj, collisionGroup)
if obj:IsA("BasePart") then
physicsService:SetPartCollisionGroup(obj, collisionGroup)
end
for _, part in ipairs(obj:GetChildren()) do
setCollision(part, collisionGroup)
end
end
function addToCollisionGroup(player, collisionGroup)
local character = player.Character or player.CharacterAdded:Wait()
for _, part in pairs(character:GetDescendants()) do
if part:IsA("BasePart") then
physicsService:SetPartCollisionGroup(part, collisionGroup)
end
end
end
function addModelToCollisionGroup(model, collisionGroup)
for _, part in ipairs(model:GetDescendants()) do
if part:IsA("BasePart") then
physicsService:SetPartCollisionGroup(part, collisionGroup)
end
end
end
function onTouched(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
local character = player.Character or player.CharacterAdded:Wait()
local key = character:FindFirstChild("Keycard")
if key then
addToCollisionGroup(player, "Default")
end
end
end
function touchEnded(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
local character = player.Character or player.CharacterAdded:Wait()
local key = character:FindFirstChild("Keycard")
if key then
addToCollisionGroup(player, playersID)
end
end
end
for _, model in ipairs(workspace:GetChildren()) do
if model:IsA("Model") and model.Name == "Barrier" then
addModelToCollisionGroup(model, barrierID)
end
end
game.Players.PlayerAdded:Connect(onPlayerAdded)
for _, model in ipairs(workspace:GetChildren()) do
if model:IsA("Model") and model.Name == "Barrier" then
for _, part in ipairs(model:GetDescendants()) do
if part:IsA("BasePart") then
part.Touched:Connect(onTouched)
part.TouchEnded:Connect(touchEnded)
end
end
end
end