如何将敌人移向一个移动的玩家?

Jim*_*med 6 sprite-kit skaction swift

我正在创建一个简单的精灵套件游戏,将玩家放置在屏幕的左侧,而敌人从右侧接近.由于玩家可以上下移动,我希望敌人"巧妙地"调整他们向玩家的路径.

我试图在玩家移动时移除并重新添加SKAction序列,但是下面的代码会导致敌人根本不显示,可能是因为它只是在每次帧更新时添加和删除每个动作,所以他们永远不会有机会移动.

希望得到一些关于创造"聪明"敌人的最佳实践的反馈,这些敌人将随时转向玩家的位置.

这是我的代码:

    func moveEnemy(enemy: Enemy) {
    let moveEnemyAction = SKAction.moveTo(CGPoint(x:self.player.position.x, y:self.player.position.y), duration: 1.0)
    moveEnemyAction.speed = 0.2
    let removeEnemyAction = SKAction.removeFromParent()
    enemy.runAction(SKAction.sequence([moveEnemyAction,removeEnemyAction]), withKey: "moveEnemyAction")
}

func updateEnemyPath() {
    for enemy in self.enemies {
        if let action = enemy.actionForKey("moveEnemyAction") {
            enemy.removeAllActions()
            self.moveEnemy(enemy)
        }
    }
}

override func update(currentTime: NSTimeInterval) {
    self. updateEnemyPath()
}
Run Code Online (Sandbox Code Playgroud)

Whi*_*ind 14

您必须在每次更新中更新敌人positionzRotation财产:方法调用.

寻找者和目标

好的,所以让我们在场景中添加一些节点.我们需要寻求者和目标.搜索者将是导弹,目标将是一个触摸位置.我说你应该在update:方法中做这个,但我会用touchesMoved方法做一个更好的例子.以下是设置场景的方法:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    let missile = SKSpriteNode(imageNamed: "seeking_missile")

    let missileSpeed:CGFloat = 3.0

    override func didMoveToView(view: SKView) {

        missile.position = CGPoint(x: frame.midX, y: frame.midY)

        addChild(missile)
    }
}
Run Code Online (Sandbox Code Playgroud)

针对

要实现瞄准,您必须根据目标计算旋转精灵的数量.在这个例子中,我将使用导弹并使其指向触摸位置.要做到这一点,你应该使用atan2函数,像这样(内部touchesMoved:方法):

if let touch = touches.first {

    let location = touch.locationInNode(self)

    //Aim
    let dx = location.x - missile.position.x
    let dy = location.y - missile.position.y
    let angle = atan2(dy, dx)

    missile.zRotation = angle

}
Run Code Online (Sandbox Code Playgroud)

请注意,atan2接受y,x顺序而不是x,y的参数.

所以现在,我们有一个角度,导弹应该去.现在让我们根据该角度更新它的位置(touchesMoved:在瞄准部分正下方添加这个内部方法):

//Seek
 let vx = cos(angle) * missileSpeed
 let vy = sin(angle) * missileSpeed

 missile.position.x += vx
 missile.position.y += vy
Run Code Online (Sandbox Code Playgroud)

就是这样.结果如下:

寻求导弹

请注意,在Sprite-Kit中,0弧度的角度指定正x轴.正角度是逆时针方向:

极地coords

在这里阅读更多.

这意味着您应该将导弹定向到右侧 导弹鼻子指向右侧 而不是向上 在此输入图像描述.您也可以使用向上导向的图像,但您必须执行以下操作:

missile.zRotation = angle - CGFloat(M_PI_2)
Run Code Online (Sandbox Code Playgroud)