This is a way of snapping to compass directions like this which can be done. I expect you’ll have the feet at a different layer below the character so that it can walk / shoot independently? You might want to try and keep track of / sync frame offset for animations when changing direction too so it feels more fluid.
-- you'll want a shared Lua module which keeps track of all enemies
local enemy = "/enemy"
function round(x)
local a = x % 1
x = x - a
if a < 0.5 then a = 0
else a = 1 end
return x + a
end
local cardinal_directions = {"e", "ne", "n", "nw", "w", "sw", "s", "se"}
local function get_compass_direction(unit_vector)
unit_vector = vmath.normalize(unit_vector)
local angle = math.atan2(unit_vector.y, unit_vector.x)
local octant = round( 8 * angle / (2 * math.pi) + 8)
octant = math.fmod(octant, 8) + 1
return cardinal_directions[octant]
end
function update(self, dt)
local position = go.get_position()
local enemy_position = go.get_position(enemy)
local target = vmath.normalize(enemy_position - position)
--print(get_compass_direction(vmath.vector3(-1,-1,0)))
print(get_compass_direction(target))
sprite.play_flipbook("#sprite", get_compass_direction(target))
end
DirectionSnap.zip (318.6 KB)