Roll20 uses cookies to improve your experience on our site. Cookies enable you to enjoy certain features, social sharing functionality, and tailor message and display ads to your interests on our site and others. They also help us understand how our site is being used. By continuing to use our site, you consent to our use of cookies. Update your cookie preferences .
×
Create a free account

[Math Check] Only want valid directions: 0, 45, 90, 135, 180, 225, 270, 315 or back to 0

1428069842
Stephen S.
Pro
Marketplace Creator
Sheet Author
API Scripter
UL UP UR LT ** RT DL DN DR Moving on a grid in the directions shown above in text (token is at **) Looking to have only 0, 45, 90, 135, 180, 225, 270, 315 or back to 0. Passing the token rotation (angle) that might be -32.222 or 634.333 (or whatever.) fixAngle = function(angle) { angle = angle % 360; angle = (angle + 360) % 360; angle = Math.round(angle / 45) * 45; angle = Math.round(angle); if(360 === angle){ angle = 0;} return angle; }, I have read Javascript: The Good Parts... and even talked to Douglas Crockford on Skype. He says this is good, just wondering if I have this correct.
1428075706

Edited 1428076338
The Aaron
Pro
API Scripter
Are you trolling me? =D I'd probably write it like this: var fixAngle = function(angle){ return (Math.round(angle/45)*45)%360 + (angle<0 ? 360 : 0); }; Your first two lines are dealing with getting a positive angle between 0 and 359, delaying that until later makes it fewer operations. I think that second Math.round() is redundant, as the first will return an integer and multiplying by another integer shouldn't introduce rounding errors... In mine, the modulus will cause the term before the + to be in the range between -315 and +315. The term to the right of the + then performs the range fix up if the result is <0. (Interesting note: the first term can result in -0, but that's still not < 0, so it's good! =D ) > _.map([-8000, -32.222, 0, 48, 359, 634.333, 8000],fixAngle); [270, 315, 0, 45, 0, 270, 90] Cheers!
1428076462
Stephen S.
Pro
Marketplace Creator
Sheet Author
API Scripter
Thanks! It felt a little long winded in the code. That could be a handly little thing. I have seen some funny decimals with obj.top and obj.left and I really didn't feel like getting bit with funny decimals from obj.rotation.
1428077042
The Aaron
Pro
API Scripter
Yeah, I have a simpler version of this in my TokenMod script, but it only bothers to keep the range in (-360, 360). (which is to say, it just mods by 360. =D)