Pardon the noob question, I am new to Roblox LUA.
I am trying to make the humanoid move forwards and backwards, (as when an officer, guards a perimeter by moving to and fro) but there may be something wrong with this script, because it only moves forwards.
local toggle = true
local RunService = game:GetService("RunService")
local humanoid = game.Players.LocalPlayer.Character:WaitForChild("Humanoid")
RunService:BindToRenderStep("Move", Enum.RenderPriority.Character.Value + 1, function()
while toggle do
humanoid:Move(Vector3.new(0, 0, -1), true)
wait(1)
humanoid:Move(Vector3.new(0, 0, 1), true)
wait(1)
end
end)
And then when I toggle = false, it does not stop.
I can't use keypress as it defeats the purpose of what I intend to do.
Thank you for any assistance.
The way this code is structured does not make much sense. You're creating a loop inside a function that is triggered every frame. Every single frame, you create a new loop... After just 10 seconds you might have 300 loops trying to move the humanoid at the same time.
Because the loops constantly overwrite each other, the last one to run takes precedence... Which is likely why it's only towards one direction.
I presume you want to make the character move towards (0,0,-1) for a second, then towards (0,0,1) for another second and then, if toggle is enabled, run again.
What you should be doing instead is not creating a loop inside the BindToRenderStep, but setting the movement every frame according to where the character should be moving to, and running that loop outside, once:
local toggle = true
local RunService = game:GetService("RunService")
local humanoid = game.Players.LocalPlayer.Character:WaitForChild("Humanoid")
movement = nil
RunService:BindToRenderStep("Move", Enum.RenderPriority.Character.Value + 1, function()
if movement then
humanoid:Move(movement, true)
end
end)
while toggle do
movement = Vector3.new(0, 0, -1)
task.wait(1)
movement = Vector3.new(0, 0, 1)
task.wait(1)
end
movement = nil
Mind that this code has some quirks:
while toggle do
. It depends on where you want to switch the toggle how you'd handle this.script.Parent:WaitForChild("Humanoid")
(though it also comes down to personal preference).true
argument to :Move()
https://create.roblox.com/docs/reference/engine/classes/Humanoid#Move. The player will still be able to move the camera to change how the movement direction.