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

How do I make a hit box for dragging items? - More detail in explanation

So I am currently making clicks visible in my game, here is a gif of what I mean: https://gyazo.com/a93b9f55c656a069aa2553fdddac7b9d

If you notice at the end of the gif, the cursor just goes infinitely in one direction, and disappears on the skybox. Instead of just limiting the distance it can travel, I want it to work like "Lumber Tycoon 2" where it has some sort of sphere (maybe even phyics if it is simple, I doubt though) of where the visual/cursor can go.

I tried putting a hollow sphere around the player and the issue is that the visual goes inside or on top of it, so that isn't going to work.

Here is my code:

player = game.Players.LocalPlayer
playerMouse = player:GetMouse()

playerMouse.Button1Down:connect(function()
	
	if workspace["Player Cursors"]:FindFirstChild(player.Name .. " cursor") then
		workspace["Player Cursors"][player.Name .. " cursor"]:Destroy()
	end	
	
	visualCursor = game.ReplicatedStorage["Visual Cursor"]:Clone()
	visualCursor.Name = player.Name .. " cursor"
	visualCursor.Parent = workspace["Player Cursors"]
	playerMouse.TargetFilter = visualCursor
	
	game:GetService("RunService").RenderStepped:connect(function()
		visualCursor.Position = playerMouse.Hit.p
	end)
end)


playerMouse.Button1Up:connect(function()
	visualCursor:Destroy()
end)

visualCursor is just a little white sphere I cloned from ReplicatedStorage.

Any suggestions how I would go about this?

1 answer

✓ Accepted answer

Clamping

You can clamp the position to an invisible sphere around the player. This will need a bit of math, but it will do the job.

-- Outside of MouseDown
local rscon;
local Torso = player.Character and player.Character:WaitForChild("Torso");
player.CharacterAdded:connect(function(c)
  Torso = c:WaitForChild("Torso");
end);

-- Inside of MouseDown.
rscon = game:GetService("RunService").RenderStepped:connect(function()
  local mpos = playerMouse.Hit.p;
  local ppos = Torso.Position;
  local diff = mpos - ppos;
  local dir = diff.unit;
  local dist = diff.magnitude;
  visualCursor.Position = ppos + dir * math.min(dist, 20) -- Clamp to 20 studs from the Torso
end)

-- Inside of MouseUp. Please remember to disconnect the RenderStepped instead of letting it error out
rscon:disconnect()

I'm going to skip the explanation for now, but if you do need the explanation just comment and I'll give you one. Also tell me if my math sucks and it's all wrong.

3 comments

0

Your math is right, even I can understand this stuff ;)

0

Can I please get an explanation, I understand the variables, but what about line 15 and how it works together?

0

Player position offset by a vector with a maximum length of 20 in the direction of the cursor.

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