Hi,
I have a challenge for all the perfectionist’s out there. Find a way to remove the 3 if statements and make it shorter. Or even turn it into one if statement…
Code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local StarterPlayer = game:GetService("StarterPlayer")
local Knit = require(ReplicatedStorage.Packages.Knit)
local ContextActionUtility = require(ReplicatedStorage.Sources.Utility.ContextActionUtility)
local calculateRelativeDirection = require(ReplicatedStorage.Sources.Utility.calculateRelativeDirection)
-- Variables
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character
local Humanoid = Character:WaitForChild("Humanoid")
-- Controller
local Movement = Knit.CreateController{
Name = "Movement"
}
local BACKWARDS_SPEED = (StarterPlayer.CharacterWalkSpeed/2)
local STRAFE_SPEED = (StarterPlayer.CharacterWalkSpeed/1.4)
function onDirection()
local rDirection = calculateRelativeDirection(workspace.CurrentCamera, Humanoid)
if rDirection == "Left" or rDirection == "Right" then
Humanoid.WalkSpeed = STRAFE_SPEED
end
if rDirection == "Backward" or rDirection == "BackwardLeft" or rDirection == "BackwardRight" then
Humanoid.WalkSpeed = BACKWARDS_SPEED
end
if rDirection == "Forward" or rDirection == "ForwardLeft" or rDirection == "ForwardRight" then
Humanoid.WalkSpeed = StarterPlayer.CharacterWalkSpeed
end
--print("Direction:",rDirection,"| Speed:",tostring(Humanoid.WalkSpeed),"| Default: "..StarterPlayer.CharacterWalkSpeed)
end
Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(onDirection)
return Movement
calculateRelativeDirection:
local calculateRelativeDirection = {}
local DIRECTION_VALUES = {
["Standing"] = {0, 0},
["Backward"] = {-1, 0},
["Forward"] = {1, 0},
["BackwardRight"] = {-1, 1},
["BackwardLeft"] = {-1, -1},
["ForwardRight"] = {1, 1},
["ForwardLeft"] = {1, -1},
["Right"] = {0, 1},
["Left"] = {0, -1}
}
local function calculateRelativeDirection(cameraInstance: Camera, humanoid: Humanoid)
local cameraRightVector = cameraInstance.CFrame.RightVector
local cameraLookVector = cameraInstance.CFrame.LookVector
local moveDirection = humanoid.MoveDirection
local lookDot, rightDot = math.round(moveDirection:Dot(cameraLookVector)), math.round(moveDirection:Dot(cameraRightVector))
for movementStatus: string, vectorData: {number} in DIRECTION_VALUES do
if vectorData[1] ~= lookDot or vectorData[2] ~= rightDot then
continue
end
return movementStatus
end
return "Standing"
end
return calculateRelativeDirection