Mouse.Hit Range

I want to create a hitbox which it’s position will be the player’s mouse position. However, I was thinking of adding a range to this. How can I do it?

local function onInputBegan(input, gameProcessed)
	
	if input.KeyCode == Enum.KeyCode.E then

		local hitbox = Instance.new("Part")
		hitbox.Parent = workspace
		hitbox.Position = mouse.Hit.Position -- the hitbox's position
        end
    end
inputservice.InputBegan:connect(onInputBegan)

Any help is welcome.

Use magnitude. More info here: Vector3 | Roblox Creator Documentation

local players = game:GetService("Players")

local player = players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local mouse = player:GetMouse()

local range = -- enter range here, the bigger the number the farther the mouse can be from the player

local function onInputBegan(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.E and (character.HumanoidRootPart.Position - mouse.Hit.Position).Magnitude <= range then
        local hitbox = Instance.new("Part")
        hitbox.Position = mouse.Hit.Position -- the hitbox's position
        hitbox.Parent = workspace
    end
end

inputservice.InputBegan:Connect(onInputBegan)

I am assuming that this a local script because you defined mouse inside the script, which is why I am using LocalPlayer

anyways I used magnitude to add range, it checks the distance between two positions
to change the range just set the range variable

4 Likes

Exactly what I was looking for. Many thanks.

There you saved me right there