How to make a max distance for part following mouse script?

  1. What do you want to achieve? Keep it simple and clear!
    So I need a part to follow my mouse so I can make ranged attacks

  2. What is the issue? Include screenshots / videos if possible!

When I hover my mouse to the sky the part will just p e r i sh

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I tried using:

local range = (hrp.Position - part.Position).magnitude
If range >= 50 then
range = 49
end

The output doesn’t even show any error

No error?!? But you have a syntax error which should be thrown by the IDE.

You don’t need an if statement to do any of this. I feel its written best when idiomatically written as:

local range = math.min(50, (hrp.Position - part.Position).Magnitude)

You can get the direction then multiply it by your range variable to limit how far away the part is.

local direction = (hrp.Position - part.Position).Unit -- Might be backwards, swap hrp & pos if they are
local finalPosition = hrp.Position + direction * range

And I would suggest using @DrKittyWaffles method of getting the range variable via math.min.

@DrKittyWaffles I didn’t copied that line from studio because I’m on mobile.

So do I just replace the local range line or do I have to rewrite the if function too?

All of this

local range = (hrp.Position - part.Position).magnitude
If range >= 50 then
range = 49
end

Can be replace with

local range = math.min(50, (hrp.Position - part.Position).Magnitude)

so where do I put it tho?

this is the full script

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local range = math.min(50, (script.Parent.HumanoidRootPart.Position - FixPart.Position).Magnitude)
game:GetService('RunService').RenderStepped:Connect(function()
	mouse.TargetFilter = c
	local pos = mouse.Hit.Position
	FixPart.CFrame = CFrame.new(pos) * CFrame.new(0,math.floor,0)
end)

You’ll want range inside the RenderStepped event so it updates

assuming you want to have the part go from the hrp to the mouse, you’ll need something like this

-- inside RenderStepped
local range = math.min(50, (hrp.Position - pos).Magnitude)
local direction = (hrp.Position - pos).Unit -- Might be backwards, swap hrp & pos if they are
FixPart.CFrame = CFrame.new(hrp.Position + direction * range)
4 Likes

It works, but there’s a problem:

You see, when I started testing, it works fine.
But when I fired a function, (aka teleporting) it became like that.