How to move an object in a direction without stopping

I am developing a small game in Swift 3 using SpriteKit, and I want to move the enemies in the direction of the character, but the enemies stop all the time when they reach the characterโ€™s initial position.

I'm doing it:

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 to move enemies in a certain direction without stopping at the initial position of the symbol?

+3
source share
2 answers

You did all the hard work by calculating the direction vector.

Now you can repeat this moveBy action as often as you like, and the enemy will continue to move in the same direction, further and further, since move(by: CGVector) is relative, not absolute:

 let actionTransaction = SKAction.move(by: movement1, duration: 20) 

So, all you need to do is start forever with the key so that you can search for it from anywhere and stop it whenever you want.

 run(SKAction.repeatForever(actionTransaction), withKey: "movingEnemy") 
+2
source

Alternatively, you can use GameplayKit along with SpriteKit. GameplayKit provides standard implementations of common algorithms for games and can be used in conjunction with SpriteKit.

Unfortunately, I am not too familiar with this, so I cannot give you the code. I would suggest taking a look at the Apple GameplayKit programming guide. There are functions that allow you to set the target of an agent (for example, an enemy) to move in a certain place, avoid obstacles, intercept another agent or flee from an agent, etc.

Thus, while your player is moving, some enemies may be programmed to try to catch the player, while other enemies may try to escape from the player. Other enemies can be made for random wandering, etc.

So, GameplayKit can add some pretty powerful functionality to a SpriteKit game. This may mean that you spend some time thinking about the architecture of your game, but in the end it may be worth it if you also use other GameplayKit features.

+1
source

Source: https://habr.com/ru/post/1013240/


All Articles