PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Creating a ClickDetector Door

Creating a ClickDetector Door

Sep 17 2018, 5:34 PM PST

The code sample below demonstrates the functionality of a ClickDetector and its properties and events.

First the code creates a ClickDetector and set’s its Instance/Parent|parent to the door. It also sets the ClickDetector/MaxActivationDistance|maximum distance players can interact with the ClickDetector to 10 studs and set’s the ClickDetector’s ClickDetector/CursorImage|CursorImage to:

Custom cursor image

Then, the code connects the ClickDetector to several events, including changing the door’s BasePart/Transparency when the player’s mouse hovers ClickDetector/MouseHoverEnter|on and ClickDetector/MouseHoverLeave|off off the door. The player opens the door by ClickDetector/MouseClick|left clicking their mouse while over the ClickDetector and closes the door by ClickDetector/RightMouseClick|right clicking their mouse while over the ClickDetector.

This code works in a Script and a LocalScript as long as the script’s parent is the door BasePart|Part.

-- The door 'BasePart'
local door = script.Parent

-- Asset ID of the image you want the to set the cursor to
local CursorId = "2287179355"

-- Create a ClickDetector
local ClickDetector = Instance.new("ClickDetector")
ClickDetector.Parent = door
ClickDetector.MaxActivationDistance = 10
ClickDetector.CursorIcon = "rbxassetid://"..CursorId

-- Make door slightly transparent when mouse hovers over it
ClickDetector.MouseHoverEnter:Connect(function()
	door.Transparency = 0.1
end)

-- Door is not transparent when mouse is not hovering over it
ClickDetector.MouseHoverLeave:Connect(function()
	door.Transparency = 0
end)

-- Open door on left mouse click
ClickDetector.MouseClick:Connect(function()
	door.Transparency = 0.8
	door.CanCollide = false
end)

-- Close door on right mouse click
ClickDetector.RightMouseClick:Connect(function()
	door.Transparency = 0.1
	door.CanCollide = true
end)