Player CFrame Control w/ Mouse

How to make the player turn towards the mouse, like in Dungeon Quest.

by NeonD00m

Author Avatar

First what you want to do is make the variables do let's start with that. To start the script, let's make a local script in StarterGui, StarterPack, StarterPlayerScripts, or StarterCharacterScripts, doesn't matter. Then call the script "MouseCharRotaterScript" for organization (optional).

VARIABLES

local player = game.Players.LocalPlayer

Then we want to get the player's mouse so lets do this:

local Mouse = plr:GetMouse()
 -- This is really useful, i suggest exploring more with this

And last but not least we will need to get something to turn around.

local Humanoid = plr.Character:WaitForChild("HumanoidRootPart")

Be careful with the above though, if you use the torso it could glitch out dure to animations creating weird orientations we don't want. So far you should have this:

local plr = game.Players.LocalPlayer
local Mouse = plr:GetMouse()
local Humanoid = plr.Character:WaitForChild("HumanoidRootPart")

Now lets start on the main part.

MAIN CODE

For the first line of code we are going to need something to make the player turn every time frame, or every time they can see the game. So we are gonna need the RunService.

game:GetService("RunService").RenderStepped:Connect(function()

(Saving the 'end)' for later) This event listener runs every frame per second so whatever we put in here will happen every time the player's screen shows the game for them. Next we need to get the mouse's 3D position and turn the player with it. so we need this:

local mousePos = Vector3.new(Mouse.Hit.p.X, Humanoid.Position.Y, Mouse.Hit.p.Z)

With the 'Mouse.Hit' we can get the mouse's 3d position so let's put it to use. So to turn the character we could use orientation but that can be problematic so let's just use CFrame, a little more advanced but can be learned quickly.

Humanoid.CFrame = CFrame.new(Humanoid.CFrame.p, mousePos)

In the above we get the players CFrame and set it to the players position, with the mouse's X and Z positions as the orientation. Then add one last line to finish it off.

end)

(If you didn't already) The resulting code should looks something like this:

local plr = game.Players.LocalPlayer
local Mouse = plr:GetMouse()
local Humanoid = plr.Character:WaitForChild("HumanoidRootPart")

game:GetService("RunService").RenderStepped:Connect(function()
    local mousePos = Vector3.new(Mouse.Hit.p.X, Humanoid.Position.Y, Mouse.Hit.p.Z)
    Humanoid.CFrame = CFrame.new(Humanoid.CFrame.p, mousePos)
end)

This is my first Lua learning article so please tell me what I should add or change about how I styled this one. Have a nice day!

View in-game to comment, award, and more!