Immediately change character's orientation / rotation after pressing a key (W, A, S, D)

using it for a 2d game so i probably only need the A and D key
i just dont know how to change the orientation to the character

3 Likes

hello

local w, a, s, d = false, false, false, false
input.InputBegan:connect(function(inputObject)
	
	
	if inputObject.UserInputType == Enum.UserInputType.Keyboard then
		if inputObject.KeyCode == Enum.KeyCode.W then
			w = true
		end
		
		if inputObject.KeyCode == Enum.KeyCode.A then
			a = true
		end
		
		if inputObject.KeyCode == Enum.KeyCode.S then
			s = true
		end
		
		if inputObject.KeyCode == Enum.KeyCode.D then
			d = true
		end
		
	end
end)

input.InputEnded:connect(function(inputObject)
	if inputObject.UserInputType == Enum.UserInputType.Keyboard then
		if inputObject.KeyCode == Enum.KeyCode.W then
			w = false
		end
		
		if inputObject.KeyCode == Enum.KeyCode.A then
			a = false
		end
		
		if inputObject.KeyCode == Enum.KeyCode.S then
			s = false
		end
		
		if inputObject.KeyCode == Enum.KeyCode.D then
			d = false
		end
		
	end
end)

--we check what keys player presses above

after this you can do something like

if a then
(set player.Character rotation here , see pictures below)
end



set the character model’s rotation according to keys I hope you get what I mean

2 Likes

You could do:

local humanoid = Character:WaitForChild("Humanoid")

humanoid.Changed:Connect(function()
	local directionRelativeToPlayer = humanoid.RootPart.CFrame:VectorToObjectSpace(humanoid.MoveDirection)
	local _,angle,_ = CFrame.new(Vector3.zero,directionRelativeToPlayer )
	humanoid.PrimaryPart.CFrame = CFrame.new(humanoid.PrimaryPart.Position) * CFrame.Angles(0,angle,0)
end)
4 Likes

after adding the missing variable it still didn’t seem to work as it says in the output “argument 2 or nil”

i’ll try this riight now

Can you show the entire script as well as the line of issue?

To change the orientation of the character, all you need to do is change the CFrame of the HumanoidRootPart.

If you want to use radians or degress:

This changed the rotation to be 75º on the Y axis:

-- Put this in StarterCharacter
local Character = script.Parent
local HRP = Character.HumanoidRootPart

HRP.CFrame = HRP.CFrame * CFrame.Angles(0, math.rad(75), 0)

Keep in mind, CFrame.Angles uses RADIANS, so you need to convert degrees.

If you want to use LookVector:

This will make the character look in the +Z direction.

-- Put this in StarterCharacter
local Character = script.Parent
local HRP = Character.HumanoidRootPart

HRP.CFrame = CFrame.LookAt(HRP.Position, HRP.Position + Vector3.new(0, 0, 1))