Question

In the following example, there are three things on the screen:

  1. ball (a SKShapeNode)
  2. spriteContainer (a SKSpriteNode that contains ball2, a SKShapeNode)
  3. box (a SKSpriteNode)

Why does ball fall out of view? Does a SKShapeNode need to be inside a SKSpriteNode to have physics properly applied to it?

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {

        SKColor * warmRed = [SKColor colorWithRed:0.99 green:0.41 blue:0.25 alpha:1.0];
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
        self.backgroundColor = warmRed;

        //falls out of view
        SKShapeNode * ball = [[SKShapeNode alloc] init];
        CGMutablePathRef ballPath = CGPathCreateMutable();
        CGPathAddArc(ballPath, NULL, size.width-40, self.size.height/2, 20, 0, M_PI*2, YES);
        ball.path = ballPath;
        ball.lineWidth = 2;
        ball.fillColor = warmRed;
        ball.strokeColor = [SKColor whiteColor];
        ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
        [self addChild:ball];

        //lands on bottom of screen
        SKShapeNode * ball2 = [[SKShapeNode alloc] init];
        CGMutablePathRef ball2Path = CGPathCreateMutable();
        CGPathAddArc(ball2Path, NULL, 0, 0, 20, 0, M_PI*2, YES);
        ball2.path = ball2Path;
        ball2.lineWidth = 2;
        ball2.fillColor = warmRed;
        ball2.strokeColor = [SKColor whiteColor];
        CGSize spriteContainerSize = CGSizeMake(40,40);
        CGPoint spriteContainerPosition = CGPointMake(size.width/2, size.height/2);
        SKSpriteNode * spriteContainer = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:spriteContainerSize];
        spriteContainer.position = spriteContainerPosition;
        spriteContainer.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:spriteContainerSize];
        [spriteContainer addChild:ball2];
        [self addChild:spriteContainer];

        //lands on bottom of screen
        CGSize boxSize = CGSizeMake(40,40);
        CGPoint boxPosition = CGPointMake(boxSize.width, size.height/2);
        SKSpriteNode * box = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:boxSize];
        box.position = boxPosition;
        box.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:boxSize];
        [self addChild:box];


    }
    return self;

}

Screenshot: https://dl.dropboxusercontent.com/u/164157126/example.jpg

Était-ce utile?

La solution

Note that you don't set a position for the node which falls off the screen, but set a position for the other two nodes you create.

The default position of a node is 0,0. Your ball will appear at the bottom left of the scene, and since it is over the edge body you defined, will fall off immediately.

Set the ball's position appropriately so that it does not intersect the edge of the screen, and the ball will not fall off.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top