1
votes

when trying to apply impulse to an SKPhysicsBody, writing the code forces a question mark, and then when using that line, it does not apply any impulse

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        player.physicsBody!.applyForce(CGVectorMake(0, 400))
    }

the physics body is initialised as such

player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size, center: CGPoint(x: player.size.width / 2, y: player.size.height / 2))

please assist

2
Have you tried it with a greater impulse, like 4000 or 40000? The physicsBody is dynamic?LearnCocos2D
I suggest you post the code that creates the sprite. There's nothing wrong with the code you posted so far.0x141E

2 Answers

1
votes

I tried that exact code and it worked fine. It could be because the player was not defined in the correct place. Make sure that player is not defined in the func didMoveToView. If it is, it should be defined right after the bracket of the SKScene.

class GameScene: SKScene {

let bird = SKSpriteNode(imageNamed: "sprite_1")

override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    self.physicsWorld.gravity = CGVectorMake(0.0, -5.0)

    bird.xScale = 2; bird.yScale = 2
    bird.position = CGPoint(x: self.frame.size.width/2.75, y: self.frame.size.height/2)
    bird.physicsBody = SKPhysicsBody(rectangleOfSize: bird.size)
    self.addChild(bird)
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        bird.physicsBody?.applyImpulse(CGVectorMake(0, 100))
    }
}

See how the player (bird for me) is not declared in the didMoveToView func.

I found this page while looking up how to apply impulses, so your post was useful to me. I hope that this can help you.

1
votes

you said you are applying "impulse" but you are applying "Force" here, which won't work in that context. I know it has been a long time but for those who come to see the solution to this problem, you can change the Force to Impulse and it should work. So,

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    player.physicsBody!.applyImpulse(CGVectorMake(0, 400))
}

There can be many other reasons such as your player mass is too huge in which case you need more impulse to move it or "player" has the wrong filename assigned to it. You will need to debug that.