Better alternatives for an infinite loop CFrame script?

I’m making an obstacle course, and I’m using CFrame a lot to give it that “original” and “fun” affect. Unfortunately, lag and performance is always an issue. I have around 10 scripts like this in my game, and I’m wondering what are better and working solutions to this.

My script currently rotates a part on the Z-axis at .075 speed using CFrame.fromEulerAnglesXYZ(). This is done within an infinite while loop, however, this is not the best practice and I was wondering if anyone knew how to resolve the lag issue.

Script:

spawn(function()
    while wait() do
        script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0,0,0.075)
    end
end)

Video:

1 Like

You could make the loop run slower or pause if the player is far from the obstacle or if the obstacle isn’t in player’s view

If all you are doing is spinning these parts, you can use HingeConstraints with a motor actuator.

1 Like

Unfortunately, most of my obstacles are like this and they are all very close to eachother making the pausing thing not work out. It also looks very choppy to increase the wait time.

you can use the cross product of the root parts vector and then the vector of both the parts and create a rotation based on the perpendicular angle given

Could you tell me how to do this or link me to tutorials please?

1 Like

Maybe perhaps remove the while wait and replace it with this.

-- The code

while true do
    script.Parent.CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(0,0,001)
    game:GetService("RunService").Heartbeat:Wait()
end

or rotate multiple parts with this

while true do                                                                                                                                                                        
    -- loop throgh the children in a model.
	for i, v in pairs(script.Parent:GetChildren()) do
        -- If child is a part then
		if (v:IsA("UnionOperation")) then
            -- rotate that part.
			v.CFrame = v.CFrame * CFrame.fromEulerAnglesXYZ(001, 0, 0)
		end
	end
	game:GetService("RunService").Heartbeat:Wait()
end

From what I can tell, it doesnt show any examples of rotating assemblies, or parts with other parts welded to it. All you need to do is use weld constraints and weld these extra parts to the part being rotated by the motor.

Thanks for all replies. This issue is now resolved after some background help with @4SHN.

1 Like