How can I make this pet only move on this part?

Hello, I have been working on a pet that hops around but I want it to only move in the range I did this:

local tweenService = game:GetService('TweenService')
local firstPart = workspace.Part
function MovePet(pet)
	local speed = math.random(.3, 2)
	local tweenInfo = TweenInfo.new(
		1,
		Enum.EasingStyle.Linear,
		Enum.EasingDirection.Out,
		0,
		false,
		0
	)
	local x = math.random(firstPart.Position.X - firstPart.Size.X/2 , firstPart.Position.X + firstPart.Size.X/2)
	local z = math.random(firstPart.Position.Z - firstPart.Size.Z/2 , firstPart.Position.Z + firstPart.Size.Z/2)

	local partBPosition = pet.Position + Vector3.new(x,0,z)
	local MiddlePosition = (pet.Position + partBPosition) / 2
	local mainPosition = MiddlePosition + Vector3.new(0,3,0)
	local tween1 = tweenService:Create(pet, tweenInfo, {Position = mainPosition})
	local tween2 = tweenService:Create(pet, tweenInfo, {Position = partBPosition})
	tween1:Play()
	tween1.Completed:Connect(function()
		tween2:Play()
	end)
	wait(3)
end

while true do
	wait()
	MovePet(workspace.MovingPart)
	wait(1)
end

But here is what happens:


How can I fix it?
Thank you!

1 Like

EDIT: I tried using path finding but it does not work.

It looks like you’re calculating X and Y positions to be within the bounds of the part, but the problem is you’re adding those X and Y positions onto the pet’s position. Instead of calculating the coordinates to go next by adding them onto the pet position, you need to set the coordinate to just X and Y.

1 Like