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

Why won't this part stop spinning when player isn't touching it?

I want the part so spin once the part is touched and stops when the player moves away. What's the problem that causes the part to now stop. If the player touches the part the spinning will get faster.

Players = game:GetService("Players")
script.Parent.Touched:connect(function(hit)
local part = script.Parent
local moving = false

while wait() do
if hit.Parent:findFirstChild("Humanoid") and moving == false then
local player = Players:GetPlayerFromCharacter(hit.Parent)
script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0,0.2,0)
moving = true
wait(.1)
elseif hit.Parent:findFirstChild("Humanoid") and moving == true then
script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0,0,0)
moving = false
wait(.1)
end
end
end)

1 answer

✓ Accepted answer

Okay, I think I figure out the problem. Took a little bit of learning for me too!

There is a type of event called TouchEnded for parts that detects whenever something stops touching mentioned part.

If you create a boolean that detects when someone is touching the part, it will do what you intend!

Here is the working code:

debounce = false
touching = false -- Created a new boolean called touching
Players = game:GetService("Players")
script.Parent.Touched:connect(function(hit)
	local part = script.Parent
	local moving = false
	
	if hit.Parent:findFirstChild("Humanoid") and not touching then
		touching = true --Since someone is touching, set this to true
		while touching do -- While someone is touching do the following...
	
				local player = Players:GetPlayerFromCharacter(hit.Parent)
				part.CFrame = part.CFrame * CFrame.fromEulerAnglesXYZ(0,0.2,0)
				moving = true
				wait(.1)
		end
	end
end)

script.Parent.TouchEnded:connect(function(hit) --  This will activate when something stops touching
	local part = script.Parent
	
	
	if hit.Parent:findFirstChild("Humanoid") then
		touching = false -- If player stops touching, set to false.  (This will stop the While loop)
		part.CFrame = part.CFrame * CFrame.fromEulerAnglesXYZ(0,0,0)
		moving = false
	end
end)

This should work, I tested it before reposting.

Let me know if you have any questions!

3 comments

0

Is it possible to move the part back to where it was before it started spinning without it being glitchy?

0

Create a new variable that saves the original CFrame, then use that variable to set it back whenever you wish.

0

k

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