How do I make a GUI move closer to my mouse when the mouse is near it

im trying to make my game’s UI have some more eye candy and i randomly though of this idea

its a bit hard to explain so i made a video:

i am not sure how i would do this but ive seen other games do it

You can use Magnitude.

local player = game.Players.LocalPlayer -- our player
local mouse = player:GetMouse() -- the mouse
local frame = script.Parent.Frame -- the frame
local oldpos = frame.Position -- frame's old position

local tweenservice = game:GetService("TweenService") -- tween service

local tween -- the tween

while task.wait() do -- loop
	local mousePos = Vector2.new(mouse.X,mouse.Y) -- mouse position in vector2
	
	if (frame.AbsolutePosition - mousePos).Magnitude < 150 then -- if distance between mouse cursor and frame is below 150 studs then
		if tween then
			if tween.PlaybackState == Enum.PlaybackState.Playing then
				tween:Cancel()
			end
		end -- If tween then end it
		tween = tweenservice:Create(frame, TweenInfo.new(1),{
		   Position = UDim2.fromOffset(mouse.X,mouse.Y)
		}) -- Moving of the frame
		tween:Play() -- playing the tween
	else -- if not then
		if tween then
			if tween.PlaybackState == Enum.PlaybackState.Playing then
				tween:Cancel()
			end
		end -- If tween then end it
		if frame.Position ~= oldpos then -- if position is not old position then
			tween = tweenservice:Create(frame, TweenInfo.new(.3),{
				Position = oldpos
			}) -- Moving of the frame
			tween:Play() -- playing the tween
		end
	end
end

Model if needed: https://www.roblox.com/library/9403297683/

3 Likes

woah what, i didnt even know you could use magnitude on that thanks

1 Like