How to move an object towards a direction without stopping

徘徊边缘 提交于 2019-12-12 09:53:45

问题


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?


回答1:


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:

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

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.

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



回答2:


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.



来源:https://stackoverflow.com/questions/41602596/how-to-move-an-object-towards-a-direction-without-stopping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!