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

How i can break loop with touched function and resume loop again?

local Model = script.Parent
Touched = false

Model.TouchPart.Touched:Connect(function()
	Touched = true
	Model:SetPrimaryPartCFrame(Model:GetPrimaryPartCFrame() * CFrame.new(0,0,0 - 198))
	Touched = false
end)

while true do
	while wait() do
		Model:SetPrimaryPartCFrame(Model:GetPrimaryPartCFrame() * CFrame.new(0,0,0 + .5))
		if Touched == true then
			break
		end
	end
end

does not break when touching a part and does not return

1 answer

✓ Accepted answer

Got in contact with OP over discord.

He wanted to make a car move along an endless road, but instead of moving the car, he wants to move the road. Visual he sent me:

The code below creates sections of road to make it appear as if a car is driving on an endless road. When the car gets near the end of the last road section, it creates a new road and adds it to a list of road sections. The script makes sure there are only two roads in game at a time.

you can test the game here

local car = workspace.DMC12 
local roadModel = game:GetService("ReplicatedStorage").Road

local ROAD_MOVE_INCREMENT = 1 --how many studs the road moves back every WAIT_TIME seconds

local roads = {}

function createRoad(cframe)
	local road = roadModel:Clone()
	road.Parent = workspace
	
	cframe = cframe or road.PrimaryPart.CFrame 
	road:SetPrimaryPartCFrame(cframe)
	table.insert(roads, road)
	
	return road	
end

local road = createRoad()

while true do
	wait()

	--once we have two roads in game,
	--remove a road section from the back of the road
	if #roads > 2 then
		local roadToDestroy = roads[1]
		table.remove(roads, 1)
		roadToDestroy:Destroy()
	end
	
	--move all the roads forward
	for _, road in pairs(roads)do
		road:SetPrimaryPartCFrame(road.PrimaryPart.CFrame * CFrame.new(0,0,-ROAD_MOVE_INCREMENT))
	end
	
	--get the road segment at the front 
	local farthestRoad =  roads[#roads]

	--spawn a new road if the car is approaching the middle of the farthest road
	local roadMiddlePosition = farthestRoad.PrimaryPart.Position.Z 
	local carFrontPosition = car.PrimaryPart.Position.Z + car.PrimaryPart.Size.Z/2
	
	if carFrontPosition  >= roadMiddlePosition  then 
		createRoad(farthestRoad.PrimaryPart.CFrame * CFrame.new(0,0,farthestRoad.PrimaryPart.Size.Z))
	end  
end

4 comments

0

it does not return

0

Why does it need to return? What is your end goal ?

0

What are you trying to return?

0

I'm thinking maybe we wants the loop to not run at all when it's not being used and be recreated again on touch?? Best to know what he wants the code to do though 

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