There some senarios in coding that come up often, bobbing up and down, wrapping a number, getting the angle between things. In these situations a bit of math can solve things in an optimised, elegant and readable way.
Sine Wave
If you want things to bob smoothly, for example an item pick up, the humble sine wave can fix it. calling sin() on the time since programmed started for the y value will make it bob from -1 to 1 smoothly every 2π seconds. Even better you can make it bob up and down every x seconds by typing sin(2π*time/x) and you can of course change the magnitude of the bob with m*sin(2π*time/x)
REM
Sometimes you want a value wrap around and REM is here to help. In most languages its operation is reffered to by the % sybmbol or in some cases the mod() function. It returns the REMainder after dividing, put simply a % b will wrap a around when its larger than or equal to b. I use this function all the time and my hearts go out to the programers who still have to write:
x = change(x);
if x >= wrap {
x -= wrap * x/wrap; // handles everything except negatives
}
instead of just: x = change(x) % wrap;
. This is also faster because REM is a single instruction while the other is multiple. But PROGRAMER BE WARE! For REM doesn't handle negatives, mod() does and rust (the language I use) has rem_euclid() which also works. In summary % wraps positive mod() wraps all. And I love her ^W^
Dot Product
Few things first, this is vector math if you've done any kind of formal course you'll know this already. But if your like me and have just been fuckin' around and finding out this is for you! You may have encontered normilisation before, making a vector length 1, well a dot product between 2 normalised vectors equals the cossine of the angles. Put simply acos(dot(a,b)) = angle between vectors! great and simple. another thing, these vectors are directions, think of it like an arrow from 0, 0(, 0) pointing to the vectors x and y (and z). if you want the direction from, lets say an enemies eyes to the player you can normalize(player_pos-eye_pos) additionally if you want to check the angle between the way the enemies facing and the direction to the player to determine if they players been spotted you can use our dot product!
let dir_to_player = normalize(player.pos - enemy.eye_pos);
let angle = acos(dot(dir_to_player, enemy.look_dir));
if angle > enemy.sight_angle { enemy.spot(player) }
granted libraries often have angle between functions. but its nice to know especialy when doing optimisation because you can drop the acos() and pre calculate the cos of an angle. ALSO dot products are used for lighting in games (dot(normal, light_dir)) which is neat! What the dot product is doing under the hood is a.x*b.x + a.y*b.y.