Hi everyone this is my first time posting here because I’m pretty new to Defold and Lua. I’m trying to write a script for the enemy in my game (2D Top down rouge like). I’m trying to get the enemy to chase the player with the following code:
function update(self, dt)
--for some reason pos DOES update every single frame but playerPos does NOT update every frame, only the first
--if this gets fixed then the enemy moving towards player will work
local playerPos = go.get_position("/player")
local pos = go.get_position()
print(playerPos)
--move up
if pos.y<playerPos.y then
self.vel.y = 40
end
--move down
if pos.y > playerPos.y then
self.vel.y = -40
end
--move left
if pos.x > playerPos.x then
self.vel.x = -40
sprite.set_hflip("#sprite", true)
end
--move right
if pos.x < playerPos.x then
self.vel.x = 40
sprite.set_hflip("#sprite", false)
end
pos = pos + self.vel * dt
go.set_position(pos)
self.vel.x = 0
self.vel.y = 0
self.correction = vmath.vector3()
end
When I print(pos) the enemy’s position is printed to console every frame. When I print(playerPos) it only prints the player’s initial position and does not update every frame. The enemy moves towards that initial position and then stops there. If anybody has any suggestions it would be greatly appreciated!
Are you absolutely sure this is the player game object that you are moving? Could it be that you have nested game objects somehow or that the game object with id “/player” actually isn’t the correct one?
I am pretty sure because it prints out the location of the player’s initial position in the console. Are there any screenshots I can send that would help explain better?
Ah, what kind of collisionobject are you using? Make sure it is kinematic or if it is dynamic you need to check “Allow Dynamic Transforms” in game.project physics section.
It’s just so weird because I have no idea what is going wrong in the enemy script because it gets the enemy’s position every frame but only gets the player’s position for the first frame(which you can see in the console it prints out the vector3 values)
Nope, what happens is that you get the position of the player game object in main.collection which holds the collectionfactory and main.script. You are not getting the position of the spawned object(s) in the player.collection. The game objects from the spawned player.collection instance will be given auto-generated ids and this is what you need to use in your enemy.script.
Now this is obviously a bit cumbersome to work with since you must pass the id of generated player instance to your enemies.
The easiest and best way forward is probably to not spawn your player using a collection factory. Instead I’d probably just add the player.collection to the main.collection.
Oh okay thank you that makes sense! I’m actually just having trouble adding the player collection into the main collection, would you be able to tell me how to do that? Sorry again, I am brand new to Defold haha