Part moving under mouse

Hello! So I have made a localscript that shoots a ray from the player’s camera to the position of their mouse and then a part moves to the end of the ray but for some reason the part is under the mouse.

I have tried changing the script so the part moves a few studs higher than the ray, but the part changes height depending on how far away it is from the camera.

here is a video of what happens:
Showcase.wmv (2.9 MB)

here is the localscript:

local runservice = game:GetService("RunService")
local uis = game:GetService("UserInputService")
local cam = workspace.CurrentCamera
local testTalble = game.Workspace:WaitForChild("TestPart") -- The part that moves to the mouse

local range = 50

local rayCastParams = RaycastParams.new()
rayCastParams.FilterDescendantsInstances = {testTalble, game.Players.LocalPlayer.Character}
rayCastParams.FilterType = Enum.RaycastFilterType.Exclude

local function changePos()
	local mouse2dpos = uis:GetMouseLocation()
	local mouse3dray = cam:ScreenPointToRay(mouse2dpos.X, mouse2dpos.Y)
	local result = workspace:Raycast(mouse3dray.Origin, mouse3dray.Direction * range, rayCastParams)
	local mouse3dposition
	if result then
		mouse3dposition = result.Position + Vector3.new(0, testTalble.Size.Y/2, 0)
	else
		mouse3dposition = (mouse3dray.Origin + mouse3dray.Direction * range) + Vector3.new(0, testTalble.Size.Y/2, 0)
	end
	testTalble.Position = mouse3dposition
end
runservice.RenderStepped:Connect(changePos)

Any help is appreciated!

It’s better to use UIS.InputChanged, you don’t need to run this every frame. This also fixes your problem, which I believe was due to UIS:GetMouseLocation() not accounting for the UI inset (top bar)

`local runservice = game:GetService("RunService")
local uis = game:GetService("UserInputService")
local cam = workspace.CurrentCamera
local testTalble = game.Workspace:WaitForChild("TestPart") -- The part that moves to the mouse

local range = 50

local rayCastParams = RaycastParams.new()
rayCastParams.FilterDescendantsInstances = {testTalble, game.Players.LocalPlayer.Character}
rayCastParams.FilterType = Enum.RaycastFilterType.Exclude

local function changePos(x, y)
	local mouse3dray = cam:ScreenPointToRay(x, y)
	local result = workspace:Raycast(mouse3dray.Origin, mouse3dray.Direction * range, rayCastParams)
	local mouse3dposition
	if result then
		mouse3dposition = result.Position + Vector3.new(0, testTalble.Size.Y/2, 0)
	else
		mouse3dposition = (mouse3dray.Origin + mouse3dray.Direction * range) + Vector3.new(0, testTalble.Size.Y/2, 0)
	end
	testTalble.Position = mouse3dposition
end

uis.InputChanged:Connect(function(inputObject, gameProcessedEvent)
	if inputObject.UserInputType == Enum.UserInputType.MouseMovement then
		changePos(inputObject.Position.X,inputObject.Position.Y)
	end
end)


``
1 Like

It works pretty well, thanks for the help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.