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

Loops that never break?

Asked by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
9 years ago

I'm currently trying to detect if a player has touched a brick in the last 5 seconds. I have tried a for loop and a repeat loop and both of them would not do the job I want. Instead of breaking the loop when the brick is touched, it just keeps going and starts another loop on top of the original one. I have a script that sets a BoolValue object to true while the brick is being moved and to false when it stops. Here is the for loop I tried:

local timesenselasttouch = 0

maxx = script.Parent.Position.X + 22
minx = script.Parent.Position.X - 5
maxz = script.Parent.Position.Z
minz = script.Parent.Position.Z - 110

script.Parent.BoolValue.Changed:connect(function(value)
repeat wait() until value == false
    for i = 1, 5 do
        timesenselasttouch = i
        wait(1)
        print(timesenselasttouch)
        if timesenselasttouch >= 5 then
            script.Parent.BodyPosition.position = Vector3.new(minx + 5, script.Parent.BodyPosition.position.Y, maxz)
            break
        end
        if value == true then
            timesenselasttouch = 0
            break
        end
    end
end)

And here is the repeat loop:

local timesenselasttouch = 0

maxx = script.Parent.Position.X + 22
minx = script.Parent.Position.X - 5
maxz = script.Parent.Position.Z
minz = script.Parent.Position.Z - 110

script.Parent.BoolValue.Changed:connect(function(value)
repeat wait() until value == false
repeat
    timesenselasttouch = timesenselasttouch + 1
    wait(1)
    print(timesenselasttouch)
    if timesenselasttouch >= 5 then
        script.Parent.BodyPosition.position = Vector3.new(minx + 5, script.Parent.BodyPosition.position.Y, maxz)
        break
    end
    if value == true then
        timesenselasttouch = 0
        break
    end
until timesenselasttouch >= 5 or value == true
end)

As previously stated, both loops don't reset and break when I touch the block a second time but rather starts another loop on top of the previous one. What can I do to detect if a player has touched the brick in the last 5 seconds?

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

It's pretty simple.

Here's the skeleton with the part keeping the time, I'm not adding any other checks or things in here.

local recent = false;

function touched(hit)
    local identifier = {hit };
    recent = identifier;
    wait(5);
    if recent == identifier then
        recent = false;
    end
end

At any other time (tracked in other events or loops), recent will be false if nothing activated touched() in the last 5 seconds;

If something did touch it, then it will be an identifier (a truey value).

0
Ahh, thank you, this is much more efficient! BlackJPI 2658 — 9y
Ad

Answer this question