Better way to make an object follow your mouse?

Currently I’m using this equation to make the object follow the mouse:
humanoidRootPart.Position + ((mouseHit.Position).Unit) * 10
Even though it does generally work, it still is a bit glitchy sometimes. Does anyone know how I can improve it?

1 Like

If anyone has any ideas please feel free to share them.

Cast a ray from the center of the camera to wherever the mouse currently is. You can use the UserInputService to figure out the exact pixel offset.

-- In a LocalScript
local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer

local Character = Player.Character or Player.CharacterAdded:Wait()
local Root = Player.Character:WaitForChild("HumanoidRootPart")

local screenParams = RaycastParams.new()
screenParams.FilterDescendantsInstances = {Character}
screenParams.FilterType = Enum.RaycastFilterType.Blacklist
screenParams.IgnoreWater = true

UIS.InputChanged:Connect(function(Input, Processed)
	if not Processed then
		if Input.UserInputType == Enum.UserInputType.MouseMovement then
			if Character.Parent and Root.Parent then
				local mouseDelta = UIS:GetMouseLocation()
				local screenRay = workspace.CurrentCamera:ScreenPointToRay(mouseDelta.X, mouseDelta.Y, 1)
				
				local hitCheck = workspace:Raycast(screenRay.Origin, screenRay.Direction * 500, screenParams)
				local hitPos = screenRay.Origin + screenRay.Direction * 500
				
				if hitCheck and hitCheck.Instance then
					-- Optional condition line to avoid looking at ghost parts
					if hitCheck.Instance.CanCollide and hitCheck.Instance.Transparency < 1 then
						hitPos = hitCheck.Position
					end
				end
				
				Root.CFrame = CFrame.new(Root.Position, Vector3.new(
					hitPos.X, Root.Position.Y, hitPos.Z
				))
			end
		end
	end
end)

Player.CharacterAdded:Connect(function(newCharacter)
	Root = newCharacter:WaitForChild("HumanoidRootPart")
	screenParams.FilterDescendantsInstances = {newCharacter}
	Character = newCharacter
end)
3 Likes

But doesn’t Mouse.Hit already do that for you?

Only technically. You can only specify a particular Instance to filter out for the Mouse object. This gives you a greater degree of control over things you do and do not want to count as objects your character can direct themselves at.

It could be improved further by adding an exception case for when the mouse is not pointing at anything at all. I forgot about that as I was writing it, but I’m sure you can figure out what to add in.

Edit: I’ve updated the code to reflect this change.

Also, one more thing. If I want to make it so that whenever the mouse’s hit changes I make the object move. I used Mouse.Move but it doesn’t work if the player moves, it only responds to mouse movement. I also tried using Mouse:GetPropertyChangedSignal(“Hit”) but for some reason that didn’t work either. I could just use run service and compare hit values with prior ones, but that’s not very optimized. Any better way of executing this?