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

How do I make this model spin when clicked, and stop when clicked again?

I am really dumb when it comes to CFrame, so sorry if this looks noobish.

local cd = script.Parent.ClickDetector
local spinningpart = script.Parent.Parent.Parent.SpinningPart

cd.MouseClick:Connect(function()
while true do
	wait()
script.Parent:SetPrimaryPartCFrame(script.Parent.Main.CFrame * CFrame.fromEulerAnglesXYZ(500,0,0))
end
end)

local isOn = true

function on()
 isOn = true
cd.MouseClick:Connect(function()
while true do
	wait()
script.Parent:SetPrimaryPartCFrame(script.Parent.Main.CFrame * CFrame.fromEulerAnglesXYZ(500,0,0))
end
end)

function off()
 isOn = false
cd.MouseClick:Connect(function()
while true do
	wait()
script.Parent:SetPrimaryPartCFrame(script.Parent.Main.CFrame * CFrame.fromEulerAnglesXYZ(0,0,0))
end
end)

function onClicked()

 if isOn == true then off() else on() end

end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

on()

Thanks if you can help.

2 answers

A simple way to achieve this is to just check a variable within the loop that is set to true while you want it to spin:

local IsSpinning = false
local Degrees = 3

cd.MouseClick:Connect(function()
	IsSpinning = not IsSpinning
end)

while wait() do
	if IsSpinning then
		script.Parent:SetPrimaryPartCFrame(script.Parent.PrimaryPart.CFrame * CFrame.Angles(math.rad(Degrees),0,0)
	end
end

Then, when you want to start spinning, you can simply go:

IsSpinning = true

And similarly to stop, you can go

IsSpinning = false

Keep in mind that the while loop is infinite, and as a result no code afterwards will be run. You will have to set IsSpinning above the while wait() do loop in the script. You can get around this by running the loop in a separate thread using spawn or coroutines, but if there is no reason to then I probably wouldn't recommend it:

spawn(function()
	--loop inside here
end)

Hope this helps!

2 comments

0

What would be a good way to be able to click it on and off assuming I'm using the first script?

0

Edited the top example

In your on and off function, you put the mouse click event inside the functions. Putting events in functions is not good. Instead, remove the events and just put the regular code in there.

function on()
    isOn = true
    --Blah blah blah your cframe coding
    --Don’t put the event here!
end

function off()
    isOn = false
    --your coding here
    --Don’t put the event here!!!!!!!!!
end

function onClick()
    if isOn then
        on()
    else
        off()
    end
end

script.Parent.ClickDetector.MouseClick:Connect(onClick) --:Connect not :connect, :connect is deprecated. I told you this in a previous answer

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