How to detect a collision in sprite kit?

Vince

I am making a game in Sprite Kit and I have struggles with the collision detection between SpriteNodes, I've set a sprite node called sprite and a sprite node called platform. I want the sprite to stop falling when collided with the platform. This is what I have:

        SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"bal.png"];
        sprite.position = CGPointMake(self.frame.size.width/4 + arc4random() % ((int)self.frame.size.width/2), (self.frame.size.height/2 + arc4random() % ((int)self.frame.size.height/2)));
        sprite.color = [self randomColor];
        sprite.colorBlendFactor = 1.0;
        sprite.xScale = 0.2;
        sprite.yScale = 0.2;
        [self addChild:sprite];
        sprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width/2];
        self.physicsWorld.gravity = CGVectorMake(0.0f, -4.0f);

        SKSpriteNode *platform = [SKSpriteNode spriteNodeWithImageNamed:@"YellowPlatform.png"];
        platform.position = CGPointMake(CGRectGetMidX(self.frame), -200+CGRectGetMidY(self.frame));
        platform.size = CGSizeMake(180, 10);
        [self addChild:platform];

Thanks in advance!

lahmar

From the Apple Documentation about SKNode and the physicsBody property:

The default value is nil, which indicates that the node does not participate in the physics simulation at all.

If you want your ball to roll on the platform or something you have to set the physicsBody property of your platform.

Additionally you have to disable the dynamic property on the platform:

A Boolean value that indicates whether the physics body is moved by the physics simulation.

Otherwise your platform would fall down/move if another physics affected object would fall on it.

Links: https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/Reference/Reference.html#//apple_ref/occ/instp/SKNode/physicsBody https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/Reference/Reference.html

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related