Range on Mouse.Hit

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to make a teleport tool that has a range limit.
  2. What is the issue? Include screenshots / videos if possible!
    I cannot figure out how to make the range and I have looked endlessly throughout the internet trying to find a solution but couldn’t find one.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I did the magnitude of the character subtracted by the mouse position but I want to make it so that you can also teleport straight up. I also tried clamping each axis of the mouse position and it worked but if the mouse was out of range, the position messed up.

Check the distance between player1(the one using the tool) and player2(the one having the tool used on them) by using HumanoidRootPart this will be accurate to check the distance between the two, OR if you are using a click to teleport to position Check the difference between where the player clicked by adding a invisible part or something. And check the distance between the player and the part.

Hey! So, instead of using Mouse.Hit, I recommend utilizing a Raycast. They are a much more efficient and configurable alternative.

I’ve left some links to the API Reference on Raycasts and related materials.

To cast a Raycast for this purpose, you want to put a LocalScipt inside of the Teleport tool. In that script you’d want to write something such as the following:

-- Services
local UserInputService = game:GetService("UserInputService")

-- Variables
local Tool = script.Parent
local Mouse = UserInputService:GetMouseLocation()

local RayParams = RaycastParams.new()
-->> If you'd like to customize the RaycastParams, do so here (check link below for more help)

-- Events

--> Fires when you use the tool
Tool.Activated:Connect(function()
      local UnitRay = workspace.CurrentCamera:ScreenPointToRay(Mouse.X, Mouse.Y)
      
      --> Now, from here, we can customize the length of the raycast to limit it
      workspace:Raycast(UnitRay.Origin, UnitRay.Direction * LENGTH, RayParams)
      --> Since LENGTH isn't a variable, you have to replace that with your desired length
end)

Let me know if this helps you any or if you have anymore questions. I’m always happy to assist.

References:
https://developer.roblox.com/en-us/api-reference/function/Camera/ScreenPointToRay
https://developer.roblox.com/en-us/api-reference/function/WorldRoot/Raycast

3 Likes

Thanks! I made it work by making the direction the unit*range of the difference between the characters’ Root and mouse position and if it did not return raycastResult, I teleported the player to the endpoint of the ray

1 Like

Alright, sounds great! Glad I was able to help :slight_smile:

Let me know if you have any other questions or need more help with this!

1 Like