How can I keep my tracks from "Overlapping"?

Hey there gamers :wave::sunglasses:. I’m making a quick cart ride game and I want my tracks to spawn in randomly. Issue I ran into is that tracks can overlap as you can see in this VIDEO :flushed:. I want to know how I can prevent the tracks from overlapping if there’s a way? Thanks for your time! :grin:

CURRENT CODE

local end_piece = script.EndPiece:Clone()
end_piece.Parent = game:GetService("Workspace")

local current_tracks = {}
while true do
	for _, track in ipairs(current_tracks) do
		track:Destroy()
	end
	table.clear(current_tracks)
	for i = 1, 25 do
		local tracks = game:GetService("ReplicatedStorage").Tracks:GetChildren()
		local track = tracks[math.random(1, #tracks)]:Clone()
		table.insert(current_tracks, i, track)
		local first_track = current_tracks[1]
		if track == first_track then
			track:SetPrimaryPartCFrame(CFrame.new(0, 0, 0))
		else
			track:SetPrimaryPartCFrame(current_tracks[i-1].End.CFrame)
		end
		track.Parent = game:GetService("Workspace")
	end
	end_piece.CFrame = current_tracks[#current_tracks].End.CFrame
	wait(0.5)
end

Can you raycast from the track placed to see if there is a path available 2 ‘spaces’ in front of it and if there isn’t place a corner to keep from running over it?
This may still cause issues if it builds into a corner though.

1 Like

You’ll either need to manually track where your tracks are (consider using a voxel system), or query Roblox using spatial queries to see if you can manually put the track down. Either way, you just need to make sure the placement is valid before picking it.

3 Likes