0
votes

I have the following code to move an "enemy" to my "players" position.

let follow = SKAction.moveTo(player.position, duration: 2)
enemy.runAction(SKAction.repeatActionForever(action), withKey: "moving")

This code works fine. However, when I move the player, I would like the SKAction to "run again" so that the enemy is always moving towards the last location that the player was at. Therefore, if the player does not keep moving, they will eventually get caught.

How come the "repeatActionForever" is not working? The enemy moves to the initial location of the player, but when you move the player to a new location, the enemy does not move to that new location.

Thanks :D

1
When you move the player you use: enemy.removeAllActions, then run the "follow" action again. - Abdou023
how is movement determined, is it 2 directional(Up/Down) 4 directional(Up/Down/Left/Right), 8 directional (U/D/L/R, all corners) or omni directional (Free to go any direction) - Knight0fDragon

1 Answers

0
votes

repeatActionForever is working, it is not dynamic, it will only move to the player at the time the action was created, it does not know anything has changed.

You need to do runBlock for this:

let follow = 
SKAction.sequence(
 [
   SKAction.runBlock(
   {
     //this will allow the enemy to constantly follow the player
     enemy.runAction(SKAction.moveTo(player.position, duration: 2), withKey:"move")
   }),
   SKAction.waitForDuration(0.1)
 ]
)
enemy.runAction(SKAction.repeatActionForever(follow), withKey: "moving")

Now the problem with this approach is your enemy speed changes based on the distance of the player. Instead you want to do this:

//duration is expected time to reach the player
let follow = SKAction.customActionWithDuration(duration,
    actionBlock: 
    {
      node,elapsedTime in
      //change the nodes velocity
      //this formula is dependent on gameplay
    })

enemy.runAction(SKAction.repeatActionForever(follow), withKey: "moving")