Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Confused about CFrame not working in clickable door. What am I doing wrong?

Disclaimer: I'm a new developer and just learned CFrames a few days ago and I wanted to apply it to my game by using it in a door.

I made a door that rotates 90 degrees when opened and -90 degrees when it is closed (toggled twice)

Here is the code:

local door = script.Parent.Door
local hinge = script.Parent.Hinge
local isOpened = false

script.Parent.Knob.ClickDetector.MouseClick:Connect(function(plr)
	
	local offset = door.CFrame * (hinge.CFrame:Inverse())
	
	if isOpened then
		hinge.CFrame = hinge.CFrame* CFrame.Angles(0,math.rad(-90),0)
		door.CFrame = hinge.CFrame *offset
		
	else
		hinge.CFrame = hinge.CFrame* CFrame.Angles(0,math.rad(90),0)
		door.CFrame = hinge.CFrame * offset
	end
	
	isOpened = not isOpened
end)

Here is what happens in the game https://gyazo.com/608bc1f0f2d9432e3c262b877dea2ba8

I don't get why it works on the first try but does not apply the offset and instead, it just rotates not relative to the hinge after the first try.

1 answer

Basically, when opening the door, you ask it to move to hinge.CFrame and it works, the opening animation does work. However, when closing, you don't ask it to go back to its first position (which i don't know but you do) but to hinge.CFrame once again (whereas it's already at hinge.CFrame)

In order for it to work, you should put the first CFrame (the door's CFrame when not opened yet) into a variable then use it after.

It should look like this : EDITED (i realized i missed something so i fixed it)

local door = script.Parent.Door
local hinge = script.Parent.Hinge
local DVariable = door.CFrame -- Just some example variable names
local HVariable = hinge.CFrame -- same here
local isOpened = false

local closedCFrame = door.CFrame -- this stores the actual door's CFrame into a variable
 
script.Parent.Knob.ClickDetector.MouseClick:Connect(function(plr)
 
    local offset = door.CFrame * (hinge.CFrame:Inverse())
    
    if isOpened then
        hinge.CFrame = HVariable
        door.CFrame = DVariable
	isOpened = false
 
    else
        hinge.CFrame = hinge.CFrame* CFrame.Angles(0,math.rad(90),0)
        door.CFrame = hinge.CFrame * offset
	isOpened = true
 
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.