Math Problems with studio

So I have been writing some custom physics for a game and it is not working

Essentially, the part gains velocity when Left (A, Arrow key, or DPad Left) is held, and velocity returns to 0 after being not held. But velocity is instead returning to 0.2. I have looked and tinkered with this code for about 10 minutes and could not fix it. Can yall help me?

if InputTable["Left"] == true then
		if VelX > -(MaxVelX) then -- Checks if the velocity is at max speed
			print("left")
			
			Part:SetAttribute("Mvmt_VelocityX", VelX - AccelX)
			
			
		end		
	else
		if VelX < 0 then -- slows 
			
			Part:SetAttribute("Mvmt_VelocityX", VelX + AccelX) 
			
			
			
			
		end		
	end

It’s possible VelX is not able to be rounded by AccelX, causing it to not go back to 0.
Simplest fix I can think of would be to clamp the speed attributes to a max / min value.

Part:SetAttribute("Mvmt_VelocityX", math.max(VelX - AccelX, -MaxVelX))

and

Part:SetAttribute("Mvmt_VelocityX", math.min(VelX + AccelX, 0))
1 Like

Why would VelX be rounded by AccelX?

If it isn’t, then the result of repeatedly subtracting can never be 0 (which is what you would want it to be). Consequently, it will overshoot the target, resulting in the 0.2 which you are seeing.

1 Like

To help counteract this, Im using division instead

			Part:SetAttribute("Mvmt_VelocityX", VelX / 2)

It reduces to 0 now

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