I’m trying to make a custom character movement system. But alas, it wasn’t as simple as i thought. I’m trying to simulate a striding motion on the z axis relative to the character whenever they’re running or walking forward or backward. If you guys have a better approach PLEASE LET ME KNOW!!! praying there’s a simpler way or something
This is my logic for the movement system:
local playerMoving = runService.RenderStepped:Connect(function(dt)
if strideMagnitude * math.sin(timer * strideFrequency) <= strideMagnitude * math.sin(math.rad(180) * strideFrequency) then
timer += dt * liftOffMultiplier
else
timer += dt
end
strideSpeed = math.clamp(strideMagnitude * math.sin(timer * strideFrequency), 0, strideMagnitude)
local moveDir = Vector3.zero
for key, _ in pairs(heldKeys) do
moveDir += keyDirections[key]
end
local root = character.HumanoidRootPart
local worldMoveDir = root.CFrame:VectorToWorldSpace(moveDir + Vector3.new(0,0,strideSpeed))
if holdingShift then
worldMoveDir *= 1.3
end
root.AssemblyLinearVelocity = worldMoveDir
end)
These are my dictionaries
--[[
Create Dictionary of values the correspond to vector3 values
]]--
local keyDirections = {
[Enum.KeyCode.W] = Vector3.new(0, 0, -runningVelocity),
[Enum.KeyCode.S] = Vector3.new(0, 0, backwardVelocity),
[Enum.KeyCode.A] = Vector3.new(-maxSidewaysVelocity, 0, 0),
[Enum.KeyCode.D] = Vector3.new(maxSidewaysVelocity, 0, 0),
}
--[[
Active Dictionary that keeps track of what keys are pressed. If the key doesn't exist in our keydirections dictionary, then don't
add it to heldKeys dictionary
]]--
local heldKeys = {}
It seems as if once you let go of the buttons it continue you should instead use the :GetMoveVector() function which you can find from the PlayerModules:
local PlayerService = game:GetService ( 'Players' )
local player = game.Players.LocalPlayer
local PlayerScripts = player.PlayerScripts
--or whatever the folder that contains all the scripts is called
-- just click the play test and go inside your player folders
local PlayerModule = PlayerScripts:FindFirstChild('PlayerModule')
local ControlModule = require( PlayerModule:FindFirstChild('ControlModule') )
--This contains most of the functions of the player movement stuff
local t = 0; -- basically variablefunction for sine to use as sine of t
local linearTime = 1 -- how long it takes to reach 1 on the t scale
---CreateConstantLoop: `````
local deltaTime = .03 -- any way for you to get delta time in a loop use it instead
local moveDirection = ControlModule:GetMoveVector()
--returns Vector3 relative to HumanoidRootpart
t = t + ( (deltaTime/linearTime) * -moveDirection.Z)
--Use negative because forward is a negative number
local sineAfy = amp * math.sin(t * Fp) -- inside frequency period and outside amp
-- you can work out the figures above and clam
local worldMoveDirection = rootPart.CFrame * moveDirection
root.AssemblyLinearVelocity = worldMoveDir * sineAfy
-- I did it in all directions so you can change it to specifically the z-axis.
--- end of the loop it how you like
can you explain :GetMoveVector? I’ve never used it in my life. Plus I have to bed so this is my last reply for today. Won’t be able to respond until 8am pst
It is a function of the Roblox player modules that returns you what direction the player is currently wanting to walk where -1 on the Z axis is forward and -1 on the x is left. I use it a lot for fly scripts
I decided to take a crack at this using a LinearVelocity. I noticed a few things in your script that stood out to me:
Your stride speed calculation doesn’t take the player’s move direction into account, erroneously applying the stride even if just strafing left and right.
I also chose to use the character humanoid’s MoveDirection value instead of checking for held movement keys directly since those represent a (world space) unit vector of where the character is trying to move. A small problem I noticed with this quick write up is that there’s a small jitter when changing directions rapidly because humanoid physics are very stubborn with external forces and velocities acting on them, but it’s not too noticeable in my testing
--[[ Variables ]]--
-- Services --
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
-- Character --
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local rootPart = character:WaitForChild("HumanoidRootPart")
-- Movement --
local mover = Instance.new("LinearVelocity")
local movementTimeAggregate = 0
local liftOffMultiplier = 9
local strideMagnitude = 9
local strideFrequency = 5
local walkspeedSideways = 15
local walkspeedBackwards = 10
local walkspeedForward = 20
--[[ Functions ]]--
local function getFlatRootCFrame() : CFrame
local rootCFrame = rootPart.CFrame
local look = (rootPart.CFrame.LookVector * Vector3.new(1, 0, 1)).Unit
if look ~= look then
local right = (rootPart.CFrame.RightVector * Vector3.new(1, 0, 1)).Unit
local look = -Vector3.yAxis:Cross(right)
return CFrame.fromMatrix(rootCFrame.Position, right, Vector3.yAxis, -look)
end
return CFrame.fromMatrix(rootCFrame.Position, Vector3.yAxis:Cross(look), Vector3.yAxis, -look)
end
local function getRelativeMoveDirection() : Vector3
local rootCFrame = getFlatRootCFrame()
local relativeMoveDirection = rootCFrame:VectorToObjectSpace(humanoid.MoveDirection)
relativeMoveDirection *= Vector3.new(walkspeedSideways, 1, 1)
if relativeMoveDirection.Z < 0 then
relativeMoveDirection *= Vector3.new(1, 1, walkspeedForward)
else
relativeMoveDirection *= Vector3.new(1, 1, walkspeedBackwards)
end
return relativeMoveDirection
end
local function moveCharacter(dt : number) : ()
local sin = math.sin(movementTimeAggregate * strideFrequency * math.pi / 2)
local strideSpeed = math.clamp(strideMagnitude * sin, 0, strideMagnitude)
local rootCFrame = getFlatRootCFrame()
local relativeMoveDirection = getRelativeMoveDirection()
local forwardsMovement = if math.abs(relativeMoveDirection.Z) > 0.01 then relativeMoveDirection.Z else 0
local strideDirection = Vector3.new(0, 0, strideSpeed) * math.sign(forwardsMovement)
local moveVelocity = rootCFrame:VectorToWorldSpace(relativeMoveDirection + strideDirection)
if UserInputService:IsKeyDown(Enum.KeyCode.LeftShift) then
moveVelocity *= 1.3
end
mover.VectorVelocity = moveVelocity
--// unsure of what exactly this does, i just put it into a variable for readability
local isLiftoff = sin <= strideMagnitude * math.sin(math.pi * strideFrequency)
if isLiftoff then
movementTimeAggregate += dt * liftOffMultiplier
else
movementTimeAggregate += dt
end
end
local function init()
humanoid.WalkSpeed = 0
local moverAtt0 = Instance.new("Attachment")
moverAtt0.Parent = rootPart
mover.Parent = script
mover.MaxAxesForce = Vector3.new(1e9, 0, 1e9)
mover.ForceLimitMode = Enum.ForceLimitMode.PerAxis
mover.Attachment0 = moverAtt0
RunService:BindToRenderStep("updateCharacterMovement", Enum.RenderPriority.Character.Value, moveCharacter)
end
init()
I’m not entirely sure of what exactly you were trying to do, so if I missed something let me know
Some food for thought: To avoid the weird physics interactions with humanoids, I think you could forgo external movers entirely and just modify the humanoid’s walkspeed depending on their move direction
It turned out better than I thought it would! The main caveat to using this walkspeed method is that you can’t set the base speed through Humanoid.Walkspeed, as the script overwrites it each frame. It does, however, prevent the physics jank from using body movers and/or velocity without needing to write custom character physics
Script
--[[ Variables ]]--
-- Services --
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
-- Character --
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local rootPart = character:WaitForChild("HumanoidRootPart")
-- Movement --
local strideFrequency = 5 --// A single stride takes 1 / frequency seconds to complete
local strideSpeed = 12
local restFrequency = 8 --// After a stride, rest for 1 / frequency seconds
local walkspeedSideways = 14
local walkspeedBackwards = 10
local walkspeedForward = 16
local currentPhaseStriding = 0
local currentPhaseResting = 0
--[[ Functions ]]--
local function isSprinting() : boolean
UserInputService:IsKeyDown(Enum.KeyCode.LeftShift)
end
local function getFlatRootCFrame() : CFrame
local rootCFrame = rootPart.CFrame
local look = (rootPart.CFrame.LookVector * Vector3.new(1, 0, 1)).Unit
return CFrame.lookAlong(rootCFrame.Position, look, Vector3.yAxis)
end
local function getMoveDirection() : Vector3
local rootCFrame = getFlatRootCFrame()
return rootCFrame:VectorToObjectSpace(humanoid.MoveDirection)
end
local function getMoveSpeedInDirection(direction : Vector3) : number
local moveVector = direction * Vector3.new(walkspeedSideways, 1, 1)
if direction.Z < 0 then
moveVector *= Vector3.new(1, 1, walkspeedForward)
else
moveVector *= Vector3.new(1, 1, walkspeedBackwards)
end
return moveVector.Magnitude
end
local function getStrideSpeed(speedScale : number) : number
local strideSine = math.sin(currentPhaseStriding * strideFrequency * math.pi) * speedScale
return strideSpeed * strideSine
end
local function advanceStridePhase(dt : number) : ()
currentPhaseStriding += dt
local finishedStride = currentPhaseStriding > 1 / strideFrequency
if finishedStride then
currentPhaseStriding = 1 / strideFrequency
currentPhaseResting = 0
else
currentPhaseResting = 1 / restFrequency
end
end
local function advanceRestPhase(dt : number) : ()
currentPhaseResting += dt
local finishedRest = currentPhaseResting > 1 / restFrequency
if finishedRest then
currentPhaseResting = 1 / restFrequency
currentPhaseStriding = 0
else
currentPhaseStriding = 1 / strideFrequency
end
end
local function updateWalkspeed(dt : number) : ()
local isStriding = currentPhaseStriding < 1 / strideFrequency
local isResting = currentPhaseResting < 1 / restFrequency
if isStriding then
advanceStridePhase(dt)
end
if isResting then
advanceRestPhase(dt)
end
local moveDirection = getMoveDirection()
local moveSpeed = getMoveSpeedInDirection(moveDirection)
if isSprinting() then
moveSpeed *= 1.3
end
local strideSpeedScale = moveSpeed / walkspeedForward
local strideWalkspeed = getStrideSpeed(strideSpeedScale)
humanoid.WalkSpeed = moveSpeed + strideWalkspeed
end
local function init()
RunService:BindToRenderStep("updateCharacterWalkspeed", Enum.RenderPriority.Character.Value, updateWalkspeed)
end
init()
Wow honestly pretty great script but I would suggest not only for this script but any other scripts that require grabbing the players move direction to instead use the PlayerModules with :GetMoveVector() Roblox provides as it doesn’t require as much calculation on what you’ll need with humanoid move direction.
I thought yours was a bit more complicated so I decided to have another run at it and made working version. Which approach would you prefer?
runService.RenderStepped:Connect(function(dt)
--Vector 3 of velocity
local velocity = humanoidRootPart.Velocity
local speed = Vector3.new(velocity.X, 0, velocity.Z).Magnitude
-- Determine intensity factor
local intensity = 0
if speed < 0.1 then
intensity = 0.1 -- idle bob intensity
elseif isSprinting then
intensity = 1 -- full sprint
else
intensity = 0.3 -- walking
end
timeElapsed += dt * (1 + speed / maxSprintSpeed) -- optional: speed-based time scale
-- Positional bob
local bobAmplitude = sprintBobAmplitude * intensity
if not isSprinting and speed > 0 then
bobAmplitude = walkBobAmplitude * intensity
elseif speed < 0.1 then
bobAmplitude = idleBobAmplitude
end
--[[
bobY and bobX gives us the Next XY position for the next frame based on time elapsed value.
Time elapsed gives us the amount of time since that last frame (essentially our never ending x in sin(x)).
We multiply by the frequency, which dictates how many full cycles per second while the
OSCILATION FORMULA dictates the amount of seconds per cycle
]]--
local bobY = math.sin(timeElapsed * math.pi * bobFrequency) * bobAmplitude
local bobX = math.sin(timeElapsed * math.pi * bobFrequency * 0.5) * sideAmplitude * intensity
-- Micro tremors (position)
--[[
adding 0, 2 and 4 creates offsets so that the xyz tremor values don't sync. Otherwise format is the exact same
]]--
local tremorScale = intensity
local tremorX = math.sin(timeElapsed * tremorFrequency + 0) * tremorAmplitude * tremorScale
local tremorY = math.sin(timeElapsed * tremorFrequency + 2) * tremorAmplitude * tremorScale
local tremorZ = math.sin(timeElapsed * tremorFrequency + 4) * tremorAmplitude * tremorScale
-- Rotational tremors
--[[
This adds rotational tremors. Except in this case, we need radians rather than degrees for later
beacuse when applying the lean rotation, CFrame.angles requires radians. Both are means of representing progress
or where we're at in a circle, but CFrame.angles just so happens to require radians
]]--
local rotX = math.rad(math.sin(timeElapsed * tremorFrequency + 6) * rotTremorX * intensity)
local rotZ = math.rad(math.sin(timeElapsed * rotTremorZFrequency + 8) * rotTremorZ * intensity)
--[[
]]--
-- Camera lean (strafe-based)
--[[
This helps determine WHERE right is. There is lots of variance when you look around with a camera. this tells
us "if we turned 90 degrees to the right, what would the cframe values be?" x,y,z. remember, x is our left right values. so if
we're moving anywhere on this axis it will be one
]]--
local rightDir = camera.CFrame.RightVector
--[[
grabs the DOT PRODUCT of the two vectors. imagine an arrow that points upward. if we have a second arrow that points to the direction that the character
moves relative to the camera, we'll get a value. If we're moving left, the value will be negative. If we're moving forward, it'll be 0.
Essentially this calculates our left right speeds.
]]--
local lateralVel = velocity:Dot(rightDir) -- positive = right, negative = left
--print(lateralVel)
--[[
Calculate the target Lean by clamping the values to a certain range. We use the maxLeanAngle
to determine the upper and lower limit. MaxLeanAngle is our max angle. It will never go higher, or lower.
Idle will be 0. 0/ anything is 0, so this will result in it being 0.
]]--
local targetLean = math.clamp(lateralVel / maxSprintSpeed, -1, 1) * maxLeanAngle
--[[
This variable will determine our current lean. We're almost done. This will go to our final camera CFrame.
What this does is grab our current lean, and gradually set it based on
math.clamp() in this line determines how fast this lerp will perform (dependent on leansmoothing. The greater the value the faster the lerp)
target-currentlean sets camera rotation for our next frame
]]--
currentLean = currentLean + (targetLean - currentLean) * math.clamp(dt * leanSmoothing, 0, 1)
--slap currentlean into a cframe.angles() so we can apply it to the camera in the end of script. Angles only takes
--radians
local leanRotation = CFrame.Angles(0, 0, math.rad(-currentLean)) -- negative to lean correctly
-- Combine rotation tremors and position changes to one cframe
local bobCFrame = CFrame.Angles(rotX, 0, rotZ) * CFrame.new(bobX + tremorX, bobY + tremorY, tremorZ)
--[[ APPLY MOVEMENTS ]]--
-- Apply relative to camera's current rotation while keeping its position
local camPos = camera.CFrame.Position
--[[
Camrot replicates the camera orientation values by grabbing the vectors that make up the camera's CFrame. There is unfortunately no such thing as
object.Rotation that automatically grabs the rotational values of the camera cframe, so this is our only way.
]]--
local camRot = CFrame.fromMatrix(Vector3.zero, camera.CFrame.XVector, camera.CFrame.YVector, camera.CFrame.ZVector)
--[[
Take the old camera Cframe, as seen in .new(camPos) and apply translations and rotations that we calculated earlier
]]--
camera.CFrame = CFrame.new(camPos) * camRot * bobCFrame * leanRotation
end)
I wrote mine the way I did because while experimenting, I ran into an issue where scaling the dt aggregate would overflow from one phase to the other. Separating the stride and resting phases allowed each phase to play out without stepping on the toes of the other so to speak
I can’t exactly tell how the code you provided would play out without some further context, but generally as far as what I think the best approach is: use what best works for you and your game. If this works and does exactly what you want it do, use it. Otherwise, try something else
:GetMoveVector() does indeed do the job in fewer steps, but I personally don’t like to depend on what I don’t fully control because they can change and break, though this is admittedly unlikely. Just a preference, both will get the job done