ahmed nader
ahmed nader

Reputation: 384

why applyImpulse is not working in swift spritekit?

In my game, when user touches screen, a bullet is created with func fire() but nothing happen.

The following is my code:

private func fire(position: CGPoint) {
        let bullet = SKShapeNode(circleOfRadius: 2)
        bullet.strokeColor = SKColor.darkGray
        bullet.fillColor = SKColor.darkGray
        let posX = (position.x) * -1
        let posY = (position.y) * -1
        let pos = CGPoint(x: posX, y: posY)
        let theta = atan2((pos.y - player.position.y), (pos.x - player.position.x))
        let finalPos = CGPoint(x: (player.position.x) + (CGFloat(playerRadius) * cos(theta)), y: (player.position.y) + (CGFloat(playerRadius) * sin(theta)))
        bullet.physicsBody = SKPhysicsBody(circleOfRadius: 2)
        bullet.position = finalPos
        bullet.physicsBody!.affectedByGravity = false
        bullet.physicsBody!.isDynamic = false
        bullet.physicsBody!.pinned = false
        numberOfBullets += 1
        bullet.name = String(numberOfBullets)
        bullet.physicsBody!.collisionBitMask = bodyType.enemy.rawValue
        bullet.physicsBody!.categoryBitMask = bodyType.bullet.rawValue
        bullet.physicsBody!.contactTestBitMask = bodyType.enemy.rawValue
        bullet.physicsBody!.usesPreciseCollisionDetection = true
        world.addChild(bullet)
        bulletForce(bullet: bullet)
    }

    private func bulletForce(bullet: SKShapeNode) {
        let dx = Double((bullet.position.x - player.position.x))
        let dy = Double((bullet.position.y - player.position.y))
        let vector = CGVector(dx: dx, dy: dy)
        bullet.physicsBody!.applyImpulse(vector)
    }

Thanks in advance.

Upvotes: 1

Views: 590

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

The reason it is failing is because you have isDynamic = false.

isDynamic means that forces can be applied to the body.

For more reading, please see: read developer.apple.com/reference/spritekit/skphysicsbody

Upvotes: 2

Related Questions