2017-04-24 80 views
1

目前我的應用程序有一個敵人,射擊子彈從敵人的任何X和Y位置,可能是朝着屏幕的底部 - 子彈的大小旅行。這是從上到下在敵方軌道上只發生一次的SKAction,這個軌跡都是隨機的X位置。Swift3 SpriteKit:角度射擊子彈

我想要做的是在4個不同的角度拍攝4發子彈。 45度,135度,225度和270度。

目前我fireBullet功能如下:

func fireBullet() { 
    let bullet = EnemyBullet(imageName: bulletImage, bulletSound: bulletSound) 
    bullet.name = "Bullet" 
    bullet.setScale(1) 
    bullet.position = CGPoint(x: enemy.position.x, y: enemy.position.y - bullet.size.height) 
    bullet.physicsBody = SKPhysicsBody.init(rectangleOf: bullet.size) 
    bullet.physicsBody!.affectedByGravity = false 
    bullet.physicsBody!.categoryBitMask = PhysicsCategories.enemy 
    bullet.physicsBody!.collisionBitMask = PhysicsCategories.none 
    bullet.physicsBody!.contactTestBitMask = PhysicsCategories.player 
    gameScene.addChild(bullet) 

    let moveBullet = SKAction.moveTo(y: -gameScene.size.height * 0.1, duration: bulletTimeInScreen) 
    let deleteBullet = SKAction.removeFromParent() 

    let bulletSequence = SKAction.sequence([moveBullet, deleteBullet]) 
    bullet.run(bulletSequence) 
} 

我假設我可以改變子彈bullet1和重複的文檔bullet2,3和4。隨着我大概可以使用zRotation旋轉每顆子彈到那個特定的角度。

我無法弄清楚是在哪個方向移動子彈。具體來說,如何從當時敵人的位置找出SKAction.moveTo的X和Y.

我已經搜索並閱讀了很多文章,但沒有一篇能夠指出我正確的方向。

+0

您想了解如何工作ATAN2,基本上你要轉換矩形座標到極座標 – Knight0fDragon

+0

@JoseCarrillo我建議你讀raywenderlich.com HTTPS的精彩教程:// WWW。 raywenderlich.com/57368/trigonometry-game-programming-sprite-kit-version-part-1 –

回答

3

我發現了一種方法,這要歸功於KnightOfDragon的這篇文章Shoot bullet in the Direction the Ship is Facing Swift and Sprite Kit,順便說一句,我用正確的方向指向了三角。

基本上我把變量名從bullet改爲bullet1,並添加了bullet2,3和4,在同一個函數中改變了zRotation。 moveBullet1 SKAction以zRotation指向的方向觸發子彈。

度數使用下面顯示的擴展名。我不記得在這個網站的哪個地方我找到了那個。

func fireBullet() { 
    let bullet1 = EnemyBullet(imageName: bulletImage, bulletSound: bulletSound) 
    bullet1.name = "Bullet" 
    bullet1.setScale(scale) 
    bullet1.position = CGPoint(x: enemy.position.x, y: enemy.position.y) 
    bullet1.zRotation = CGFloat(45.degreesToRadians) 
    bullet1.physicsBody = SKPhysicsBody.init(rectangleOf: bullet1.size) 
    bullet1.physicsBody!.affectedByGravity = false 
    bullet1.physicsBody!.categoryBitMask = PhysicsCategories.enemy 
    bullet1.physicsBody!.collisionBitMask = PhysicsCategories.none 
    bullet1.physicsBody!.contactTestBitMask = PhysicsCategories.player 
    gameScene.addChild(bullet1) 

    let moveBullet1 = SKAction.move(to: CGPoint(
     x: distance * cos(bullet1.zRotation) + bullet1.position.x, 
     y: distance * sin(bullet1.zRotation) + bullet1.position.y), 
     duration: bulletTimeInScreen) 
    let deleteBullet1 = SKAction.removeFromParent() 

    let bullet1Sequence = SKAction.sequence([moveBullet1, deleteBullet1]) 

    bullet1.run(bullet1Sequence) 
} 


extension Int { 
    var degreesToRadians: Double { return Double(self) * .pi/180 } 
    var radiansToDegrees: Double { return Double(self) * 180/.pi } 
} 

Four bullets shot in different directions.