Acceleration and deceleration system bug

Hello, I am trying to make an acceleration and deceleration system. The problem is that the tweens seem to bug while in a heartbeat loop. I have no idea how to fix this though since the heartbeat loop is needed to check the way the player is moving. Any help is appreciated.

Video of the bug:

Code: (The function is connected to Humanoid:GetPropertyChangedSignal(“MoveDirection”))

function Movement:Accelerate()
		
	if self.Humanoid.MoveDirection ~= Vector3.zero and self.Humanoid.WalkSpeed <= self.MaxSpeed and self.Accelerating == false then
		
		self.Connections[1] = game:GetService("RunService").Heartbeat:Connect(function(DeltaTime)
			
			if table.find({"Forward", "ForwardLeft", "ForwardRight"}, self.MovingDirection) then
				
				self.Accelerating = true
				
				TweenService:Create(self.Humanoid, TweenInfo.new(self.AccelerationTime), {WalkSpeed = self.MaxSpeed}):Play()
			
			else
				
				self.Accelerating = false
				
				TweenService:Create(self.Humanoid, TweenInfo.new(self.DecelerationTime), {WalkSpeed = self.NormalSpeed}):Play()
			
			end
			
		end)
	
	elseif self.Humanoid.MoveDirection == Vector3.zero then
		
		if self.Connections[1] then
			
			self.Connections[1]:Disconnect()
			
			self.Humanoid.WalkSpeed = self.NormalSpeed
			self.Accelerating = false
			
		end

	end
	
end
1 Like

I don’t recommend using tweens in a Heartbeat event. Heartbeat fires every frame during the physics simulation, and since tweens already update every frame, this can create performance issues and redundancy. Instead, consider using an easing function to smoothly increase or decrease the value. When you click on one of the functions, scroll down to the Math Function section. You’ll find a block of TypeScript code that you can reference to create a similar function in Lua, as their syntax is quite similar.

1 Like