Numbers never returning to 0?

I’m scripting a steering portion for a boat control, but I use a value of 0-1 multiplied by the turn speed rate to achieve smooth steering.

I’m using a VehicleSeat for this, and when the seat’s Steer value is at 0 it will slowly return the turning speed back to 0. However, I noticed that the seat still slightly turns, and I used print statements to find out what the problem was.

Here is the turning portion of the script (it’s in a while true do loop):

local TurnAccelerationRate = Configuration.TurnAccelerationRate.Value

local TurnThrottle = 0

while true do
    if Main.Steer == 0 then
		if TurnThrottle > 0 and TurnThrottle ~= 0 then 
			TurnThrottle = TurnThrottle - TurnAccelerationRate
		elseif TurnThrottle < 0 and TurnThrottle ~= 0 then
			TurnThrottle = TurnThrottle + TurnAccelerationRate
		end
    end
end

…and here are the statements it prints out when I checked the throttle values:

As you can see, the value never returns to 0 but an extremely small number.

How would I go about solving this?

What kind of Value is your TurnAccelerationRate variable? I think what you’re looking for is a IntValue:

It’s a NumberValue, since IntValue can’t be a decimal.

1 Like

This is a floating point error caused by the NumberValue. A way to fix it is to round it to the nearest thousandth. TurnThrottle = math.round(TurnThrottle*1000)/1000 would work.

Or just do:

if TurnThrottle >= .001 then  
	TurnThrottle = TurnThrottle - TurnAccelerationRate
elseif TurnThrottle <= -.001 then 
	TurnThrottle = TurnThrottle + TurnAccelerationRate
elseif TurnThrottle < .001 and TurnThrottle > -.001 then
	TurnThrottle = 0
end
1 Like

Also, TurnThrottle ~= 0 is redundant as the first condition confirms that TurnThrottle is not equal to zero.

2 Likes

I’ve actually just ended up using math.abs to round to 0. This works.

if Main.Steer == 0 then
		if math.abs(TurnThrottle) < TurnAccelerationRate then
			TurnThrottle = 0
		elseif TurnThrottle > 0 then 
			TurnThrottle = TurnThrottle - TurnAccelerationRate
		elseif TurnThrottle < 0 then
			TurnThrottle = TurnThrottle + TurnAccelerationRate
		end
	end