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
I mean the total frame offset of the animation not the number of compass directions. So you don’t have to restart an animation every time you change directions, you can change its offset within sprite.play_flipbook() to match the current fame that would be playing on the sprite. Unless restarting the animation looks fine.
Imagine you did have a running animation, it might look off to constantly restart the total animation cycle every time you changed direction, but if you kept track of the current offset the sprite is playing at by counting frames you can make changing direction look smooth.