4

I made this simple effect of a ball bouncing off the screen. It only works with the top and bottom edges but I don't know why. Besides, when I try this code in an iOS 7 SpriteKit template in the initwithsize method it works. Is this a bug or something?

#import "GameScene.h"

@implementation GameScene

-(void)didMoveToView:(SKView *)view {
    self.backgroundColor = [SKColor whiteColor];
    SKSpriteNode *ball =[SKSpriteNode spriteNodeWithImageNamed:@"ball"];
    ball.position =CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.frame.size.width/2];
    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    self.physicsWorld.gravity = CGVectorMake(0, 0);
    CGVector impulse =     CGVectorMake(20,20);
    [self addChild:ball];
    
    [ball.physicsBody applyImpulse:  impulse];
    
    ball.physicsBody.restitution = 1;
    ball.physicsBody.friction = 0;
    ball.physicsBody.linearDamping = 0;
    
  /* 
   SKSpriteNode *wall =[SKSpriteNode spriteNodeWithImageNamed:@"wall"];
   
   SKSpriteNode *bar =[SKSpriteNode spriteNodeWithImageNamed:@"bar"];

   wall.position= CGPointMake(self.frame.size.width/2, 103);
    bar.position = CGPointMake(self.frame.size.width/2,  (wall.frame.size.height));
    [self addChild:wall];
    [self addChild:bar];
   
    */
    
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71

2 Answers2

1
  1. You did not set anchor node which is very important set it to CGPointMake(0.5,0.5)

  2. The gravity vector should be set to (0,-9.8) but it is (0,0) change it too.

Now your problem,

You have to set anchor to (0.5,0.5) for both ball and your rect whatever it is(self) and you need to set physics body half of the size you are allocating.

By seting the anchor to the center of your body (0.5,0.5) you are telling the physics engine to set the physics body by considering center as origin and in this case you need to set half of the sides length and for the ball you have to set the radious.

But how ios7 works I really surprised, it shouldn't but I wish both work after these corrections.

Rassam
  • 30
  • 8
  • I realized something is wrong with my stimulator because when i create the sprite kit project the hello world label doesnt fully appear in the screen – Mohamed AbouGhazala Sep 07 '15 at 11:29
1

What Rassam said about anchor point is not accurate, the position by default is at (0.5,0.5).

Its obvious it has something to do with size of the scene. Your scene is wider than your screen. NSLog the width of the scene to test my hypothesis.