I'm developing a small game in Swift 3 with SpriteKit and I want to move the enemies to the direction of the character, but at all times the enemies stop when they arrive at the character's initial position.
I'm doing this:
enemigo.name = "enemigo"
enemigo.position = CGPoint(x: 280, y: 100)
enemigo.xScale = 1/1
enemigo.yScale = 1/15
addChild(enemigo)
let movement1 = CGVector(
dx: (enemigo.position.x - personaje.position.x)*10,
dy: (enemigo.position.y - personaje.position.y)*10
)
let actionTransaction = SKAction.move(by: movement1, duration: 20)
enemigo.run(actionTransaction)
How should I move the enemies to a specific direction without stopping at the initial position of the character?
Alternatively, you could consider using GameplayKit together with SpriteKit. GameplayKit provides standard implementations of common algorithms for games and can be used together with SpriteKit.
Unfortunately I'm not too familiar with it, so I can't give you code. I would suggest having a look at Apple's GameplayKit programming guide. There are functions available for setting a goal of an agent (e.g. an enemy) to move toward a specific location, avoid obstacles, intercept another agent, or flee from an agent, etc.
So while your player moves, some enemies could be programmed to try and catch the player, while other enemies could try to run away from the player. Other enemies could be made to wander around randomly, etc.
So in a nutshell, GameplayKit can add quite powerful functionality to a SpriteKit game. This could mean spending a bit more time upfront thinking about the architecture of your game, but in the end it could be worth it if you will also use the other functionalities of GameplayKit.
You've done all the hard work figuring out the vector of direction.
Now you can repeat this moveBy action as often as you like, and the enemy will keep moving in the same direction, further and further, because
move(by: CGVector)
is relative, not absolute:So all you need do is run this forever with a key, so you can then seek it out from anywhere, and stop it whenever you like.