How to detect a collision in sprite kit?

好久不见. 提交于 2020-01-13 18:01:46

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/19337067/how-to-detect-a-collision-in-sprite-kit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!