Problem with using VectorToObjectSpace() to get a characters move direction

So I’ve been working on a script for my game which gets the movement info of a character, which works fine forwards and backwards, but when I try and move left and right without moving forwards at all, it only gives the correct output at certain angles.

local RunService = game:GetService("RunService")

local Player = game.Players.LocalPlayer
local Character = Player.Character
local Humanoid = Character:WaitForChild("Humanoid")
local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

local function GetMovementInfo()
	local Direction = HumanoidRootPart.CFrame:VectorToObjectSpace(Humanoid.MoveDirection)
	if Direction.Z < 0 then
		print("Player is moving forwards")
	elseif Direction.Z > 0 then
		print("Player is moving backwards")
	elseif Direction.Z == 0 and Direction.X < 0 then
		print("Player is moving left")
	elseif Direction.Z == 0 and Direction.X > 0 then
		print("Player is moving right")
	else
		print("Player is not moving")
	end
end

RunService.RenderStepped:Connect(function()
	GetMovementInfo()
end)

If moving left and right, when I used a print() command to check the Direction value, it had extremely large/small values on the Z axis, when it should just be 0

The code was working fine for a while, but it randomly stopped working when I did nothing to it.
If anyone has the solution or another way of finding out the move direction of a character, it would be much appreciated.

1 Like

You can use :Dot() on the MoveDirection vector and pass the camera CFrame’s LookVector or RightVector (depending on which direction you’re checking for) to find the direction.

Also, you should use :GetPropertyChangedSignal() instead of a RenderStepped connection.

local players = game:GetService("Players")

local player = players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")

local camera = workspace.CurrentCamera

local function moveDirectionChanged()
    local moveDirection = hum.MoveDirection
    if moveDirection.Magnitude > 0 then
        print("Player is moving")
        if moveDirection:Dot(camera.CFrame.LookVector) > 0.5 then
            print("Player is moving forward")
        elseif moveDirection:Dot(camera.CFrame.LookVector) < -0.5 then
            print("Player is moving backward")
        elseif moveDirection:Dot(camera.CFrame.RightVector) > 0.5 then
            print("Player is moving right")
        elseif moveDirection:Dot(camera.CFrame.RightVector) < -0.5 then
            print("Player is moving left")
        end
    else
        print("Player is not moving")
    end
end

hum:GetPropertyChangedSignal("MoveDirection"):Connect(moveDirectionChanged)
1 Like

Thanks, its all working fine, I didn’t know that Dot() was a thing, makes things much easier.

1 Like

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