Ticking a number down to zero no matter if it's positive or negative

Hi! Very simple coding question I hope. Lets say I have a value that controls the amount of force placed on an object in a 2d vector: (like {0, 0} being no force applied, {1, 0} being force applied to left {0, 1} being forced applied downwards and etc.)

Now, overtime I would like these force values to deplete till the value itself reaches zero. Is there any formula/function that will do this with relative ease?


local object = {
       x = 0,
       y = 0,
       force = {0, 0}
}

function update(dt)
      object.x = object.x + force[1]
      object.y = object.y + force[2]

      -- a way to do this with if statements would be
      --[[

       if force[1] > 0 then 
          force[1] = math.clamp(force[1] - dt, 0, math.huge)
       elseif force[1] < 0 then
          force[1] = math.clamp(force[1] + dt, -math.huge, 0)
       end

       if force[2] > 0 then 
          force[2] = math.clamp(force[1] - dt, 0, math.huge)
       elseif force[2] < 0 then
          force[2] = math.clamp(force[1] + dt, -math.huge, 0)
       end
      --]]
      -- but is there a simpler way of doing this?
end

there is a much shorter way to do that exact thing :slightly_smiling_face:
force[n]-=math.sign(force[n])*dt
math.sign just returns -1 or 1 depending on the sign(+/-) of the inputted value

1 Like

You can make it fewer lines of Lua by letting math library functions handle all the conditionals internally, like:

for i = 1, #force do
	force[i] = math.sign(force[i]) * math.max(0, math.abs(force[i])-dt)
end
1 Like

THANK U!!! (character limit thing blah blah blah)

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