SemAllush
SemAllush

Reputation: 479

SpriteKit Physics not working

I made a sprite according to apple's programming guide, but when the game starts, the sprite should fall (according to the guide), but it doesn't.

Here is how I did it:

- (void) createContents {
    self.backgroundColor = [SKColor colorWithRed:0.1 green:0.6 blue:0.8 alpha:1];
    self.scaleMode = SKSceneScaleModeAspectFill;

    SKSpriteNode *player = [self newPlayer];
    player.name = @"player";
    player.position = CGPointMake(CGRectGetMidX(self.frame), player.size.width/1.5);

    [self addChild:player];
}
- (SKSpriteNode *) newPlayer {
    SKSpriteNode *aPlayer = [[SKSpriteNode alloc]initWithColor:[SKColor whiteColor] size:CGSizeMake(40,40)];
    aPlayer.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:aPlayer.size];


    return aPlayer;
}

the createContent method is called by didMoveToView

Why doesn't it, like apple stated in the guide, plummet through the bottom of the screen

Upvotes: 1

Views: 665

Answers (3)

Scott
Scott

Reputation: 1222

Use the Cmd+Shift+F find to search for a few things.

  1. Make sure you haven't accidentally set .dynamic = NO;
  2. Make sure you haven't accidentally set the physics world gravity to something undesirable. (Like 0, 0)
  3. Very important one... make sure you are initing self.physicsBody such as...

self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

Upvotes: 0

jonogilmour
jonogilmour

Reputation: 673

Likely because you aren't setting the scene's gravity property.

In your SKScene:

self.physicsWorld.gravity = CGVectorMake(0,x) // replace x with your desired gravity magnitude and direction (I suggest -9.8)

Upvotes: -1

Peter
Peter

Reputation: 1109

I believe the player did drop to the bottom screen, but it is too fast that you missed it. Since, there is no physical body on the bottom of the screen to stop it and your player is created straight after the scene is shown on the screen.

There are two simple ways to prove it:

  • if you set aPlayer.physicsBody.affectedByGravity = NO; you will see aPlayer node floating around.

  • if you change [self addChild:player]; to [self performSelector:@selector(addChild:) withObject:player afterDelay:4.0];, you will surely observe after 4 seconds, aPlayer suddenly appear and drop to bottom of the screen

and you should set the Y position of aPlayer to higher value to see more of the falling process. In SpriteKit coordinate system, (0,0) coordinate is on bottom left corner

Upvotes: 2

Related Questions