Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Making the player look toward your mouse?

I have been trying to figure this out for an hour now and have gotten nowhere. Cut my life in to pieces, this is my last resort.

Basically I'm trying to get the player to rotate only on the y-axis but this code here will rotate the player model on all axis':

local m = game.Players.LocalPlayer:GetMouse()

if (player.Character.HumanoidRootPart.Velocity).magnitude < 1 then
		player.Character.HumanoidRootPart.CFrame = CFrame.new(player.Character.HumanoidRootPart.Position, m.Hit.p)		
	end

If someone could help me out, point out an easier method, That'd be wonderful.

1 answer

Put this in StarterPlayer.StarterCharacterScripts

local RunService = game:GetService("RunService")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Character = Player.Character or Player.CharacterAdded:Wait()
local Torso = Character:WaitForChild("Torso")

local pi = math.pi
local atan2 = math.atan2
local newCFrame = CFrame.new
local newCFrameAngles = CFrame.Angles
local Dir, TorsoPos

RunService.RenderStepped:Connect(function()
	if Torso then -- Don't run once Torso is removed
		TorsoPos = Torso.Position
		Dir = (Mouse.Hit.p - TorsoPos).unit
		Torso.CFrame = newCFrame(TorsoPos) * newCFrameAngles(0, atan2(Dir.X, Dir.Z) + pi, 0)
	end
end)

EDIT: Removed local declaration of Torso. It stopped the code from working. My bad.

This discussion is preserved as it was. New answers, comments, and votes are closed.