Looking for best way to handle this Angle checking function

Hi, so I have this Angle code which I am using to check the Angle of a HingeConstraint. Currently, it works fine, but I am not satisfied with how I wrote it. Is there any better way I can write this?

function CheckWheelAngle(ang)
	if ang < -165 then return 1
	elseif ang < -135 then return 2
	elseif ang < -105 then return 3	
	elseif ang < -75 then return 4	
	elseif ang < -45 then return 5
	elseif ang < -15 then return 6	
	elseif ang < 15 then return 7	
	elseif ang < 45 then return 8
	elseif ang < 75 then return 9	
	elseif ang < 105 then return 10	
	elseif ang < 135 then return 11	
	elseif ang < 165 then return 12	
	else return 1	
	end
end

Any help is appreciated, thanks.

Perhaps something like this?

local function CheckWheelAngle(ang)
	if (ang >= 165 or ang < -165) then return 1 end
	local value, count = -165, 1
	repeat
		value += 30; count += 1
	until ang < value
	return count
end

I. EDIT
Results are now identical (accidentally deleted a minus when posting).

II. EDIT (2021-03-01) @matiss112233
I tested the speed of both functions (mine and the one posted by @fret13103). Both are extremely fast, needing only Xe-7 to Xe-6 seconds to return any result. To my BIG surprise, my function involving repeat loop is a little more consistent and minimally faster on a micro level, meaning it can return the result under 10e-6 s more often. The difference is completely negligible (surprising for me, because I though loop would be slower), and I also like fret13103’s version, because it looks clean and compact.

2 Likes

I’m liking how organized that looks, I’ll be sure to try it, thank you!

Edit: I have tried it out, basically what this does is check the angle right? Well, when testing, it was extremely off, meaning some calculations are wrong. I’m not sure if this is an error on your end, or I wrote it wrong, but it seems to be off with detection.

local function CheckWheelAngle(ang)
    if ang < -165 or ang > 164 then return 1 end 
    local rel = ang + 165
    return 2 + math.abs(math.floor((rel)/30))
end

Your code is readable as is, but if you really want to change it to something more compact, I tested this and it gave the same results for all values in the range -180, 180

you can also store abs and floor locally instead of indexing math and you’ll avoid table indexing when you call them but that’s a totally pointless micro optimisation.

2 Likes