I have a calculation that’s running per frame, and I wanna figure out an efficient way to do it, it’s used for a character controller.
Here is a simplified version
local part: Part = workspace.Part
-- calculate velocity
local speed = 10
local velocity = Vector3.new(0, 0, -1) * speed * deltaTime
-- calculate rotation
local rotSpeed = 10
local currentRot = part.CFrame.Rotation
local targetRot = CFrame.new(Vector3.zero, velocity.Unit)
local finalRot = currentRot:Lerp(targetRot, rotSpeed * deltaTime)
-- combine both
local finalPos = part.Position + velocity
local cf = CFrame.new(finalPos) * rotationCF
-- change the up vector
local upVector = Vector3.yAxis
local finalCF = CFrame.fromMatrix(finalPos, cf.XVector, upVector, cf.ZVector)
-- apply it to part
part.CFrame = finalCF
My goal is to apply velocity, rotation and make sure the part’s up vector is aligned with the world’s up vector (y axis) each frame.
Here is the how I currently do it:
- calculate the velocity vector → direction * speed * delta time
- make a cframe with no translation and rotation based on the velocity vector
- combine both velocity (translation) and rotation into a single cframe
- create a third cframe with all the second cframe data but with a modified up vector to match the world’s up vector
I’m not sure if this is efficient, I’m creating a lot of objects here, is there a better way to do it? perhaps by changing the way I calculate and apply rotation?