Unable to keep a moving part in a certain range

I’m an early intermediate scripter, and I’m making a game to practice scripting. I was making a movement system for a part that tweens it randomly around the map and, was unable to find a way to keep the part in a certain range.

The script I have made:

for i =1,999999 do
	local tweenservice = game:GetService("TweenService")
	local Tornado = script.Parent
	local random3 = math.random(5,10)
	local info = TweenInfo.new(random3,
		Enum.EasingStyle.Linear,
		Enum.EasingDirection.InOut,
		0,
		false
	)
	local random1 = math.random(-50,50)
	local random2 = math.random(-50,50)
	local newposition = Tornado.Position + Vector3.new(random1, 1.5, random2)
	local tween = tweenservice:Create(Tornado, info,{Position = newposition})
	
	random1 = math.random(-50,50)
	random2 = math.random(-50,50)
	random3 = math.random(5,10)
	tween:Play()
	task.wait(1)
end

I know this probably isn’t the right way to do this, but I’m still learning, and was unsure on how else to do it.

One way I tried to keep it in a certain range was to every half second check if it was within the certain range I wanted, but it wouldn’t work and would just give me an error, even after I made many changes to it to try and fix it.

I am unsure on how to keep it in a certain range, and any help would be appreciated!

1 Like

This is happening because you are adding a random position offset to the CURRENT position of the tornado each time. Instead, you want to create an origin point and rotate it about there.

Also switch to a while loop, what you’re doing isn’t necessary.

local Tornado = script.Parent

local origin = Tornado.Position -- The starting point, keep randomzing it this THIS POINT
local tweenservice = game:GetService("TweenService")

while true do
	local random3 = math.random(5,10)
	local info = TweenInfo.new(random3,
		Enum.EasingStyle.Linear,
		Enum.EasingDirection.InOut,
		0,
		false
	)
	local random1 = math.random(-50,50)
	local random2 = math.random(-50,50)
	local newposition = origin + Vector3.new(random1, 1.5, random2)
	local tween = tweenservice:Create(Tornado, info,{Position = newposition})

	random1 = math.random(-50,50)
	random2 = math.random(-50,50)
	random3 = math.random(5,10)
	tween:Play()
	task.wait(1)
end

It works perfectly! Thank you for helping and also explaining what caused it not to work!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.