Making model follow cursor

I have a spotlight with scripts that allow it to move based on when I press all WASD keys, just like player controls.

This is how it looks with these controls:


However, I want to figure out a way to make it so that the spotlight follows the cursor with the same movements of the arm and head of the spotlight. Basically, the arm turns towards the cursor on an X-axis, and the head follows the cursor on a Y-axis.

[EDIT] An extra thought, if the spotlight follows the cursor, is there a way to make it sort of delayed, to give the movement a smooth look to it?

[EDIT2] Forgot to show the code.

Here is the code of the W Key script:

local userInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local SpotlightHead = game.Workspace.Spotlight1.Arm.Head
local UpdateCon

userInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.UserInputType ~= Enum.UserInputType.Keyboard then return end
	if input.KeyCode ~= Enum.KeyCode.W then return end

	if UpdateCon then
		UpdateCon:Disconnect()
		UpdateCon = nil
	end

	UpdateCon = RunService.Heartbeat:Connect(function(dt)
		local newCFrame = SpotlightHead.PrimaryPart.CFrame * CFrame.Angles(-0.05, 0, 0)
		SpotlightHead:SetPrimaryPartCFrame(newCFrame)
	end)
end)

userInputService.InputEnded:Connect(function(input, gameProcessedEvent)
	if input.UserInputType ~= Enum.UserInputType.Keyboard then return end
	if input.KeyCode ~= Enum.KeyCode.W then return end
	if not UpdateCon then return end

	UpdateCon:Disconnect()
	UpdateCon = nil
end)

Any help is appreciated! :slight_smile:

2 Likes

Mouse cursor is 2D, and light is 3D. I think something to do with camera too…

Use a quick while loop or use RunService and grab the player’s Mouse.Hit each loop to grab its world position. You’ll have to do some math on the axes to move the arm & the head of the spotlight to look toward the world position.

Use TweenService if you’d like to add a delay when the spotlight follows the cursor.

Use this to get the Origin and the Direction of the raycast, and now you can get the position of the mouse curser, material, part, and everything you need

You can use this to get the Origin and the Direction of the raycast, and now you can get everything you need