How do i fix the dragging system in my game?

I’m making a game where the player can drag objects using his mouse. Most of the game is already done, but when the player drags the object, it almost instantly goes into the middle of the player’s camera. How can i counteract this? I already looked for solutions on here.

Here is my script so far:


local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

-- var defining 2

local selBlock
local dragBall

-- var defining 3

local dragging = false

-- inputbegan block (what happens when the player is attempting to drag a block)

UIS.InputBegan:Connect(function(input)
	if mouse.Button1Down and mouse.Target ~= nil and mouse.Target:HasTag("draggable") then
		dragging = true
		print(mouse.Target)
		selBlock = mouse.Target
		-- what happens when the block is being dragged
		-- visuals set up
		dragBall = Instance.new("Part", selBlock)
		dragBall.Size = selBlock.Size + Vector3.new(2, 2, 2)
		dragBall.Color = Color3.new(0.00392157, 0.784314, 1)
		dragBall.CanCollide = false
		dragBall.Transparency = 0.75
		dragBall.CFrame = selBlock.CFrame
		dragBall.Shape = Enum.PartType.Ball
		local wc = Instance.new('WeldConstraint', dragBall)
		-- drag mechanics set up
		wc.Part0 = dragBall
		wc.Part1 = selBlock
		
		while dragging == true do
			task.wait()
			selBlock.CFrame = mouse.Hit
		end
	end
end)

--inputended block (what happens when the player is no longer dragging a block)

UIS.InputEnded:Connect(function(input)
	if mouse.Button1Up and dragging == true then
		dragging = false
		if mouse.Target ~= nil then
			print("-" ..selBlock.Name)
		end
		dragBall:Destroy()
		selBlock = nil
	end
end)
1 Like

mouse.Target is conflicting with the actual object itself, so when you try and drag it, it actually detects itself instead of what you want it to. You can fix it using mouse.TargetFilter.

The mouse object is not recommended for use and only isn’t deprecated due to it’s already widespread use. When you can, it’d be better to switch to a raycasting system from the position on screen.

2 Likes

I don’t think i made myself clear; im talking about this piece of code

while dragging == true do
			task.wait()
			selBlock.CFrame = mouse.Hit
		end

which makes the object go to the mouse, but it should be at a distance from the camera and not going right into it like its doing now.

1 Like

Well, that code will move it to the mouse, so I don’t see why it should be at a distance. If you want it to move to the floor, you can perform a raycast to the floor and move it there, accounting for it’s Y size. Is selBlock a BasePart?

1 Like

After some logical thinking and testing i realized that you helped me and i was too tired to realize :slight_smile:

2 Likes