I need to generate a number that goes from 0 to 180 where >30< is 0 and 15 is 180, been playing around with this a bit and I almost had it except it’s inverted and it’s based on 0 to 30
local ammo = 30
for i = ammo, 0, -1 do
print(math.ceil((i / ammo) * 180))
end
-- When ammo is 30, number is 180
-- When ammo is 0, number is 0
I’m entirely clueless at this point, any help is appreciated.
I think you’re looking for what is called a linear mapping operation. A linear mapping operation proportionally transforms a value between one range to another range. This is a fairly useful and common algorithm that is used in many applications. You can find a Lua implementation of the Linear Mapping function on RosettaCode:
--[[
Source from RosettaCode:
@param a1 (number) The lower bound of the range to map from
@param a2 (number) The upper bound of the range to map from
@param b1 (number) The lower bound of the range to map to
@param b2 (number) The upper bound of the range to map to
@param s (number) The value in the range [a1,a2] to be mapped to [b1,b2]
@returns (number) The value 's' mapped from [a1,a2] to [b1,b2]
--]]
function map_range( a1, a2, b1, b2, s )
return b1 + (s-a1)*(b2-b1)/(a2-a1)
end
Sub in your ammo value to ger a number between 0-180.
Example:
f(0) = 1/5(0)^2 = 0
f(30) = 1/5(30)^2 = 180
Edit: Not sure what value should equal what value. Your code says 0 should get 0, and 30 should give 180. Your title says otherwise. Let me know if this is the one you need.
Edit:
You flipped your numbers between the reply and your topic … here are equations for both:
15 : 0, 30 : 180 ((x-15)/15)*180
15 : 180, 30 : 0 (1-(x-15)/15)*180
A tips for coming up with equations and relationships like this:
I always try to break things into alpha values. An alpha value is (at least in this case) a number from 0-1. For this equation the alpha is either (1-(x-15)/15) or ((x-15)/15). One of the reasons alpha values are nice is because it’s easy to flip them (reverse their trend) by doing 1-alpha (like I did to flip the trend between the 15-30 number here).
Edit 2: @V3N0M_Z has a great solution for a non-linear equation.