I want to add a range limit however every solution I tried causes the aim to be changed

Sorry if the title sounds misleading, I didn’t know how else to phrase it. Anyway, I’ve been trying to make a beam/laser(?) ability. So to decide the end of the beam and where the raycast should end I used an attachment and that attachment’s position is decided by Mouse.Hit.Position. However, I want to add a range limit of 80 studs. The solution I tried ended up with the beam ending going to the void or stay awaing from the mouse when the mouse crosses the 80 stud range.

However what I want to achieve is to make the beam to continue to go towards the mouse. For example, if you were to put your mouse in the sky, the beam would go up into the sky however it’d only be 80 studs in length.

First solution I tried:
c4c82da2290dd4c77f7794b2cd863564

if (Facing-HMRP.Position).magnitude > 80 then
			local NewFacing = HMRP.Position + Facing*(80/(HMRP.Position - Facing).Magnitude)
			FinalEffect.Position = NewFacing
		else
			FinalEffect.Position = Facing
		end
1 Like

Instead of using the player’s mouse, you can use the mouse position on the screen, it’s the same, but it’s easier to modify since Raycast will be used, and it accepts more parameters than Mouse.Hit.

Function
local function GetWorldPosition(BasePosition: Vector3, Position: Vector3|Vector2, length: number)
	local UnitRay = workspace.CurrentCamera:ScreenPointToRay(Position.X, Position.Y)
	local Result = workspace:Raycast(UnitRay.Origin, UnitRay.Direction * length)
	if Result then
		return Result.Position
	else
		return BasePosition + (UnitRay.Direction * length)
	end
end
  • BasePosition: the Vector3 base in the world.
  • The resulting Vector3 is the position of the end of your ray.
How to use

If you use InputChanged, you can get the position of the input

game:GetService("UserInputService").InputChanged:Connect(function(Input)
	if Input.UserInputType == Enum.UserInputType.MouseMovement then
		local Position = GetWorldPosition(BasePosition, Input.Position, 80)
		print(Position)
	end
end)

else, you can use GetMouseLocation and subtract GuiInset

local UIS = game:GetService("UserInputService")
local GuiInset = game:GetService("GuiService"):GetGuiInset()

local Position = GetWorldPosition(BasePosition, UIS:GetMouseLocation() - GuiInset, 80)
print(Position)
1 Like

I get the error message “attempt to perform arithmetic (add) on nil and Vector3” on the “return BasePosition + (UnitRay.Direction * length)” line

Did you define the 3 values? check if BasePosition is a Vector3.