z_mirror/flib
git clone https://git.raiguard.me/z_mirror/flib
ca6c4a4
trunk
1local flib_math =require ( "__flib__.math" ) 2 3--- Functions for working with directions. 4--- ```lua 5--- local flib_direction = require("__flib__.direction") 6--- ``` 7--- @class flib_direction 8local flib_direction ={} 9 10--- Calculate the opposite direction. 11--- @param direction defines.direction 12--- @return defines.direction 13function flib_direction . opposite ( direction ) 14return ( direction + 8 ) % 16 --[[@as defines.direction]] 15end 16 17--- Calculate the next four-way or eight-way direction. 18--- @param direction defines.direction 19--- @param eight_way? boolean 20--- @return defines.direction 21function flib_direction . next ( direction , eight_way ) 22return ( direction + ( eight_way and 2 or 4 )) % 16 --[[@as defines.direction]] 23end 24 25--- Calculate the previous four-way or eight-way direction. 26--- @param direction defines.direction 27--- @param eight_way? boolean 28--- @return defines.direction 29function flib_direction . previous ( direction , eight_way ) 30return ( direction + ( eight_way and - 2 or - 4 )) % 16 --[[@as defines.direction]] 31end 32 33--- Calculate an orientation from a direction. 34--- @param direction defines.direction 35--- @return RealOrientation 36function flib_direction . to_orientation ( direction ) 37return direction / 16 --[[@as RealOrientation]] 38end 39 40--- Calculate the direction of travel from the source to the target. 41--- @param source MapPosition 42--- @param target MapPosition 43--- @param round? boolean If true, round to the nearest `defines.direction`. 44--- @return defines.direction 45function flib_direction . from_positions ( source , target , round ) 46local deg =math . deg ( math . atan2 ( target . y - source . y , target . x - source . x )) 47local direction =( deg + 90 ) / 22.5 48if direction < 0 then 49direction =direction + 16 50end 51if round then 52direction =flib_math . round ( direction ) 53end 54return direction --[[@as defines.direction]] 55end 56 57return flib_direction