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:
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
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)
local UIS = game:GetService("UserInputService")
local GuiInset = game:GetService("GuiService"):GetGuiInset()
local Position = GetWorldPosition(BasePosition, UIS:GetMouseLocation() - GuiInset, 80)
print(Position)