How to make a model glide downwards when a ClickDetector is pressed?

Hi!

I’m trying to make it so that one of my models slowly lowers/glides itself downwards when a certain ClickDetector is activated?

How do I make it so that it moves slowly downwards and I can always change the speed in the script?

Thanks.

1 Like

This should get you started. The comments should explain it but if you have any questions ask away.

In my test place I added a part, added a script, pasted in this code, anchored the part, positioned it at 10 on the Y axis. Hop in game and click the part, part falls to Y 1 then on a second click returns to Y 10.

There are other ways to do crete the same effect with Tweens, CFrames and/or using while loops vs heartbeat but this maybe enough for your use case.

--"Script" attached to the part

local part = script.Parent --get the part, needs to be anchored is this case
local partLocation = part.Position --the original location of the part
local speed = 0.01 --distance in studs per beat the part will move
local goalY = 1 --end position along y
local connection --connection to the Heartbeat sevice
local cd = Instance.new("ClickDetector", part) --adds a ClickDetector to the part
local moving = false --not moving by default

cd.MouseClick:Connect(function()
	
	if moving then --cancel the click if already moving
		print("Ignoring click.")
	return end --jump out of the function
	
	if part.Position.Y <= goalY then --part has already dropped down
		resetPart() --move the part back to it original position
	else	
		dropPart() --move the part down to it's goal position
	end
	
	moving = true --serves as a debounce
end)

function dropPart()
	connection = game["Run Service"].Heartbeat:Connect(function()
		
		--part.Position = Vector3.new(part.Position.X, part.Position.Y - speed, part.Position.Z) --lower the part along Y
        part.Position -= Vector3.new(0, speed, 0) --cleaner statement
		print("Part is now at: " .. part.Position.Y)
		
		if part.Position.Y <= goalY then --if at goal height stop and disconnect
			print("Part has reached it's goal of " .. goalY)
			moving = false --reset the debounce
			connection:Disconnect() --disconnect from the heartbeat service
		end
	end)
end

function resetPart()
	connection = game["Run Service"].Heartbeat:Connect(function()
		
		---part.Position = Vector3.new(part.Position.X, part.Position.Y + speed, part.Position.Z) --raise the part along Y
        part.Position += Vector3.new(0, speed, 0) --cleaner statement
		print("Part is now at: " .. part.Position.Y)
		
		if part.Position.Y >= partLocation.Y then --if at original location
			print("Part has reached it's goal of " .. partLocation.Y)
			moving = false --reset the debounce
			connection:Disconnect() --disconnect from the heartbeat service
		end
	end)
end

EDIT: Changed the Vector3 statements to be more readable

Use tweenservice -

When the click detector is pressed, tween the part to its goal location.