Jess
Jess

Reputation: 3146

Why isn't SKSpriteNode responding to applyForce or applyImpulse?

I have a sprite node that's appearing and falling in response to the gravity applied on its attached physicsBody.

Great.

Now, I'd like to use applyForce to push it a little bit in some direction while it's falling.

Unfortunately, no matter how small I make the physicsBody.mass or physicsWorld.gravity or how large I make the applyForce vector -- the applyForce vector appears to be ignored.

When I comment out the self.physicsWorld.gravity line, I see applyForce working as expected

How do I achieve "pushing" the physics body using applyForce whilst gravity is applied?


Here's my .h

// GameScene.h


#import <SpriteKit/SpriteKit.h>

@interface GameScene : SKScene

@end

And the .m

// GameScene.m

#import "GameScene.h"

@interface GameScene ()
@property NSMutableArray *bubblesToPop;

@end

@implementation GameScene

-(void)didMoveToView:(SKView *)view {
    /* Setup your scene here */

    self.size = view.bounds.size;
    self.physicsWorld.gravity = CGVectorMake(0, 1.0);

    SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"bubble"];

    sprite.yScale = 0.5;
    sprite.xScale = 0.5;
    sprite.name = @"bubble";
    sprite.position = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0);

    SKPhysicsBody *physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.frame.size.width];
    physicsBody.mass = 0.02;
    [physicsBody applyForce:CGVectorMake(900, 900)];
    sprite.physicsBody = physicsBody;

    [self addChild:sprite];

}

@end

Upvotes: 4

Views: 1904

Answers (1)

0x141E
0x141E

Reputation: 12753

The body needs to be in the scene before Sprite Kit can determine how a force will affect it. The applyForce call on the physics body needs to happen after you addChild to the scene.

From Apple's documentation:

The physics simulation in Sprite Kit is performed by adding physics bodies to scenes. A physics body is a simulated physical object connected to a node in the scene’s node tree. It uses the node’s position and orientation to place itself in the simulation...Each time a scene computes a new frame of animation, it simulates the effects of forces and collisions on physics bodies connected to the node tree. It computes a final position, orientation, and velocity for each physics body. Then, the scene updates the position and rotation of each corresponding node [emphasis added].

Also, external factors contribute to how a physics body is affected by a force. For example, gravity, collisions, and force fields (iOS 8) must be taken into account when calculating the net force that is applied to a physics body. Therefore, the body needs to be in the scene before Sprite Kit can determine how a force will affect it.

Upvotes: 5

Related Questions