Character keeps swaying back and forth due to camera script

  1. What do you want to achieve? Keep it simple and clear!
    I want to make the character look at the mouse pointer but only in the x and z axes.

  2. What is the issue? Include screenshots / videos if possible!
    The script works but the character keeps swaying back and forth. It only bugs for R6 character, but I want to keep the game R6.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    ChatGPT didn’t fare well this time either. I searched a bit through the forum but I didn’t see any. I tried setting CFrame differently but nah didn’t work.

local UIS = game:GetService("UserInputService")

local player = game:GetService("Players").LocalPlayer
local character = player.Character

local rayParams = RaycastParams.new() do
	rayParams.FilterType = Enum.RaycastFilterType.Exclude
	rayParams.FilterDescendantsInstances = {character}
end

local function getMousePos()
	local length = 1000
	local mousePos = UIS:GetMouseLocation()
	local ray = workspace.CurrentCamera:ScreenPointToRay(mousePos.X, mousePos.Y)
	local raycast = workspace:Raycast(ray.Origin, ray.Direction * length, rayParams)
	if raycast then
		return raycast.Position
	end
	return ray.Direction * length
end

while task.wait() do
	local mousePos = getMousePos()
	character.PrimaryPart.CFrame = CFrame.new(character.PrimaryPart.Position) * CFrame.lookAt(character.PrimaryPart.Position, Vector3.new(mousePos.X, character.PrimaryPart.Position.Y, mousePos.Z)).Rotation
end

This can be done way easier:

--// Variables

local Player = game:GetService("Players").LocalPlayer -- Gets the Player
local Mouse = Player:GetMouse() -- Gets the Mouse

local Character = Player.Character or Player.CharacterAdded:Wait() -- Gets the character
local HumanoidRootPart = Character.HumanoidRootPart or Character:WaitForChild("HumanoidRootPart") -- Gets the HumanoidRootPart

--// Main Code

game:GetService("RunService").RenderStepped:Connect(function() -- Starts a loop that fires every frame, prior to the frame being rendered
	
	local RootPosition, MousePosition = HumanoidRootPart.Position, Mouse.Hit.Position -- Gets the position of the HumanoidRootPart as well as the mouse

	HumanoidRootPart.CFrame = CFrame.lookAt(RootPosition, Vector3.new(MousePosition.X, RootPosition.Y, MousePosition.Z)) -- Changes the HumanoidRootParts CFrame to point towards the mouses X and Z
	
end)
1 Like

I guess I will take the big fat L and use mouse.hit.Position. People say that player:getmouse will be superseded so thats why I used custom mouse function. Thanks

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