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

If statement doesnt work for checking if Position is reached or not?

Asked by 6 years ago

So I've been trying to make a part that Goes from starting position to the end position when another part is touched then connected it to a function and a for loop inside it to increase the the Y axis by .5, then I did an if statement to check if its reached its maximum position, and if it didn't it would execute the event touched then connect it to the function to make it go up, but the if statement didn't work.. Here's my script:

MovedPart = script.Parent
MoverScript = MovedPart.Mover
TouchEqualMove = workspace.TouchE
debounce = false
MaxPos = workspace.MaxPosOfMovedPart
StartingPos = workspace.StartingPosOfMovedPart
h = 0
function Ontouched(part)
    if not debounce then
        debounce = true
        if game.Players:GetPlayerFromCharacter(part.Parent) then
                print(part.Name)
                for i = .5, 10.5, .5 do
                h = h + .5
                MovedPart.Position = Vector3.new(40, h, -22)
                print (MovedPart.Position)
                wait(.5)
            end
        end
        wait(2)
        debounce = false
    end
end
if MovedPart.Position == MaxPos.Position then
    print("Max position reached!")
elseif MovedPart.Position == StartingPos.Position then
    TouchEqualMove.Touched:connect(Ontouched)
end

The problem is that the if statement isn't checking if MovedPart.Position == MaxPos.Position but executing the elseif statement which is already done, so when i touch it again (where MaxPos is (40, 10.5, -22) it goes up in Y axis like so: (40, 21, -22) and so on on the Y-axis Is there something wrong with the If statement?

0
try 'if MovedPart.Position == Vector3.new(MaxPos.Position) then' Nikkulaos 229 — 6y
0
Didn't work either :/ yassofi 0 — 6y

2 answers

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

While yes theoretically a constant check will solve the issue, another problem is that the parts position will probably never be exactly equal to the other parts. You should be using magnitude to check how close it is instead.

http://wiki.roblox.com/index.php?title=Magnitude

while ((MovedPart.Position - MaxPos.Position).magnitude > 1) do --[[Adjust as needed.]]
    print("Max position not reached.")
    wait(nil)
end
print("Max position reached.")
Ad
Log in to vote
0
Answered by 6 years ago

Your if statement is running one time when the game loads and then stops checking. If you want it to continue checking, you should put it into a loop. Another solution, however, would be to swap your for loop for a

while MovedPart.Position ~= MaxPos.Position do

I believe this should solve your problem.

Answer this question