Sergio Toledo Piza
Sergio Toledo Piza

Reputation: 788

Swift: How to make bullet spawn at player weapon?

I have a class CharacterCreator which makes the player and inside it I have these functions to make the player shoot:

func shoot(scene: SKScene) {
    if (playerArmed) {
        let bullet = self.createBullet()
        scene.addChild(bullet)
        bullet.position = playerWeaponBarrel.position
        bullet.physicsBody?.velocity = CGVectorMake(200, 0)
    }
}

func createBullet() -> SKShapeNode {
    let bullet = SKShapeNode(circleOfRadius: 2)
    bullet.fillColor = SKColor.blueColor()
    bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.frame.height / 2)
    bullet.physicsBody?.affectedByGravity = false
    bullet.physicsBody?.dynamic = true
    bullet.physicsBody?.categoryBitMask = PhysicsCategory.Bullet
    bullet.physicsBody?.contactTestBitMask = PhysicsCategory.Ground
    bullet.physicsBody?.collisionBitMask = PhysicsCategory.Ground
    return bullet
}

The playerWeaponBarrel child node is where the bullet should spawn. What happens is that when I call the shoot() function at GameScene:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let touchedNode = self.nodeAtPoint(location)

        if (touchedNode == fireButton) {
            Player.shoot(self.scene!)
        }

it just won't create the bullet at the playerWeaponBarrel. How do I make this happen?

Upvotes: 1

Views: 480

Answers (1)

luk2302
luk2302

Reputation: 57184

Your problem is that the playerWeaponBarrel.position is relative to its super node, which is probably the player. But you want the bullet to be located absolutely in the scene, not relative to the player. Therefore what you need to do is convert the playerWeaponBarrel.position from its local coordinate system to the scene coordinate system:

bullet.position = scene.convertPoint(playerWeaponBarrel.position, fromNode: playerWeaponBarrel.parent!)

Upvotes: 1

Related Questions