Moving spawned tanks to player

Hi, I am very new to defold. I am working on the war tuorial and stuck at a spot.
I am creating tanks at random location. Now i need the tanks to move towards the player. Can someone help me out with this.

function spawn_tank(self, dt)
	self.timer = self.timer - dt
	if self.timer <= 0 then
		self.timer = 2
		id = factory.create("#tankfactory", vmath.vector3(math.random(100,500), math.random(100,500), 0))
	end
end

I can get the player position using go.get_position("player"). But can’t figure out how to get all the spawned tanks to the player after a short delay. I tried set_position but couldn’t manage to get it to work.

Welcome to Defold.

You could animate the movement to the player position:

go.animate(id, "position", go.PLAYBACK_ONCE_FORWARD, go.get_position("player"), go.EASING_LINEAR, 5)

The 5 is the time taken (in seconds). You could replace the 5 with a variable time depending on the speed of the tank.

local speed = 100 --pixels per second
local distance = vmath.length(go.get_position("player") - go.get_position(id))
local t = distance / speed

For reference, using set_position it would be:

go.set_position(go.get_position("player"), id)

Not so useful for your case, since it would just instantly place the tank on the player.

4 Likes

Hey @Alex_8BitSkull Thank you very much works like a charm :smiley: . In my case the payer position comes something like (x,y,1) when I give this in animate tank is not show. I have to give it as (x,y,0) (I might have changed something somewhere).
Next i will start working on moving tank again once it stops so it doesn’t stay at a place for long.
Again tvm for the quick response.

This sample project could also be of help in your case: How many sprites can you have on screen before slowdown? - #15 by britzl

1 Like