Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to set limits to how far the mouse can select a target?

I'm making a game where the player has to click objects to activate them. I used the mouse property of the player. Here's and example of what my script looks like,

--In a local script in StarterPack
local mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:connect(function()
	local Target = mouse.Target
	if Target and Target.Name == "ChangePlatform" then
		Target:Destroy()--Example
	end
end)

However, the player is able to click the object from an extreme distance. How can I limit this distance?

I tried looking this question up but couldn't find a solution.

You might have to get the player's torso and measure the distance from the torso and the object but I don't know how to do that. Also, if you do this would it cause a lot of lag?

Any help would be awesome.

Thank You.

2 answers

✓ Accepted answer

Ok, ednojacks answer is good and all, but magnitude is so much easier!

--In a local script in StarterPack
player = game.Players.LocalPlayer
local mouse = player:GetMouse()
maxDistance = 30

mouse.Button1Down:connect(function()
    local Target = mouse.Target
    if Target and Target.Name == "ChangePlatform" then
        local mag = (player.Character.Torso.Position-Target.Position).magnitude
        if mag <=30 then
            Target:Destroy()--Example
        end
    end
end)

I'm assuming you already know how to use magnitude, but if you don't, leave a comment and I'll clarify.

2 comments

0

Great wanseer! This will help me in make problem greatly.

0

:D I worked very hard on my wanseer! But what did you think of my answer?

Rays. Solves erry'tang.

local poopslosh = game.Workspace.Camera
local player = Players.LocalPlayer
if player.Character then
poopslosh = player.Character
end
local mouse = game.Players.LocalPlayer:GetMouse()
mouse.Button1Down:connect(function()
	local target = mouse.Target
	if target then
        local mRay = mouse.UnitRay
        local mDistance = 100
        local ray = Ray.new( mRay.Origin, mRay.Direction * mDistance)
        local part, pos, normal = game.Workspace:FindPartOnRay( ray, poopslosh )
		if part then
			if part.Name == "ChangePlatform" then
				part:Destroy() 
			end
		end
	end
end

Added the character player definition.

4 comments

0

What?

0

Magnitude is only 1 extra line!

0

Ok, a couple extra lines....

0

And you never defined player

This discussion is preserved as it was. New answers, comments, and votes are closed.