Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
yoshi8080 445 Moderation Voter
9 years ago

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

Log in to vote
0
Answered by
Necrorave 560 Moderation Voter
9 years ago

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!

0
Is it possible to move the part back to where it was before it started spinning without it being glitchy? yoshi8080 445 — 9y
0
Create a new variable that saves the original CFrame, then use that variable to set it back whenever you wish. Necrorave 560 — 9y
0
k yoshi8080 445 — 9y
Ad

Answer this question