将SKSpriteNode移动到触摸方向

时间:2017-09-21 13:49:29

标签: swift sprite-kit skaction

在这里你有一个游戏的版画屏幕:

enter image description here

我有一个静止的SKSpriteNode(播放器),它向触摸方向旋转。这是我的代码:

class GameplayScene: SKScene, SKPhysicsContactDelegate {

static let Pi = CGFloat(Double.pi)
static let DegreesToRadians = Pi / 180

override func touchesMoved(_ touches: Set<UITouch>, with event: 
UIEvent?) {
    let curTouch = touches.first! as UITouch
    let curPoint = curTouch.location(in: self)

    let deltaX = self.player.position.x - curPoint.x
    let deltaY = self.player.position.y - curPoint.y
    let angle = atan2(deltaY, deltaX)

    self.player.zRotation = angle + 90 * GameplayScene.DegreesToRadians
}
}

现在,我想每秒从玩家那里射击子弹,这些玩家的移动方向与触摸屏幕相同。当子弹移动到屏幕之外时,我想实现&#34; SKAction.removeFromParent&#34;。

这是我的fireMissile函数:

func fireMissile() {
    let missile = SKSpriteNode(color: .yellow, size: CGSize(width: 20, 
    height: 5))
    missile.name = "Missile"
    missile.position = CGPoint(x: player.position.x + 30, y: 
    player.position.y)
    missile.zPosition = 2
    missile.physicsBody = SKPhysicsBody(rectangleOf: missile.size)
    missile.physicsBody?.isDynamic = false
    missile.physicsBody?.categoryBitMask = ColliderType.Bullet
    missile.physicsBody?.collisionBitMask = ColliderType.Enemy
    missile.physicsBody?.contactTestBitMask = ColliderType.Enemy

    self.addChild(missile)

}

1 个答案:

答案 0 :(得分:1)

对于计时器,您将要使用此功能:

run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
        yourFunction()
        }, SKAction.wait(forDuration: 1)])), withKey: "key")

对于导弹射击,按顺序添加SKActions。第一个应该将子弹放在你的玩家面前,第二个将移动导弹,第三个将删除,但这只会在其他线路之后由于序列而运行。如果要在动画中期稍后停止,请确保您具有此序列的键。应该看起来像这样:

missile.zRotation = player.zRotation
missile.position = CGPoint(x:player.size.width/2*cos(player.zRotation)+player.position.x ,y:player.size.height*sin(player.zRotation)+player.position.y)
 missile.run(SKAction.sequence([SKAction.move(to: CGPoint(x:frame.size.width*cos(player.zRotation)+player.position.x ,y:frame.size.height*sin(player.zRotation)+player.position.y), duration: 0.5), SKAction.removeFromParent()]), withKey: "move")