How do I change sprite texture based on direction to enemy (SOLVED)

What is easiest way to do this?

I have 3d model I created, I exported them in a 1/4 top down view of all 9 cardinal directions:

Layer%202(pasted) Layer%204(pasted) Layer%205(pasted) Layer%206(pasted) Layer%208(pasted) Layer%209(pasted) Layer%2010(pasted) Layer%2011(pasted)

How do I get the sprite texture to change based on the direction to the enemy?

OR can I some how easily just use the and rotate the 3d model in a 2d map to face the enemy? or would the whole map / collection have to be 3d?

Thank you for your help!

direction

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)

3 Likes

Nope he doesnt walk just rotates. :slight_smile:

Thank you I will try this out.

1 Like

When you say offset your talking about the number of positions - like 16 instead of 8?

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. :slight_smile:

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.

1 Like

Ah!