How can I convert this while loop to a Runservice.Heartbeat loop?

Hi DevForum,

I acknowledge that there has been a post somewhat similar to this, but this case is somewhat different.

I want to convert this while loop:

local testpart = workspace.TestPart

local yinitialSpeed = 1

local ySpeed = yinitialSpeed
local xSpeed = 1
local gravityRate = 10
local gravityExponentIncrease = 2.5
local intervalTime = 0.1

local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
bodyVelocity.Parent = testpart

while true do
	local xVelocity = testpart.CFrame.LookVector * xSpeed
	local yVelocity = testpart.CFrame.UpVector * ySpeed
	
	bodyVelocity.Velocity = (xVelocity + yVelocity)
	
	if ySpeed <= 0 then
		gravityRate += gravityExponentIncrease
		
		ySpeed -= gravityRate
	else
		ySpeed -= gravityRate
	end
	
	wait(intervalTime)
end

To a RunService.Heartbeat loop so it can be more efficient and can be disconnected. Help would greatly be appreciated, thank you!

(If you want to know what this does in short, it is a projectile motion simulation basically, where the part moves as the x component of the velocity stays constant, and y constantly decreases due to “gravity”)

1 Like

You can convert this to a disconnect able RunService.Heartbeat by doing:

connection = RunService.Heartbeat:Connect(function()

end)

and adding the stuff done within the while loop into it.

You can disconnect this by using connection:Disconnect()

I have tried doing that, but it just doesn’t work. I know I need to use deltaTime if im handling velocity or position and all that but its just really confusing on how to switch it.

If you replace the while true bit with the Heartbeat connection, you can use the deltaTime value to calculate what you need to add / multiply the values by.

Looking at the code, the lines which would need to have their values multiplied are lines 22, 24, and 26, namely this if statement:

if ySpeed <= 0 then
	gravityRate += gravityExponentIncrease
		
	ySpeed -= gravityRate
else
	ySpeed -= gravityRate
end	

If you times it by (deltaTime / intervalTime), then it the values should all change at the same rate as when you were using a while loop.

if ySpeed <= 0 then
	gravityRate += gravityExponentIncrease * (deltaTime / intervalTime)
end	
ySpeed -= gravityRate * (deltaTime / intervalTime)
1 Like

Thank you for explaining it with such detail!

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