Sprite Kit Collision Detection

▼魔方 西西 提交于 2019-11-28 12:45:34
user3480028

The basics for setting upp collision between 2 objects is to first setting upp constant that represent the different objects that can collide. I usually make a constants.h file where i keep all the variables that will be used thru out the game/application.

Declare following in either a constants.h file or just declare them as global variables in the class:

static const int balloonHitCategory = 1;
static const int spikeHitCategory = 2;

What you want to do now is set up the physics for both your balloon and spikes

SKSpriteNode *ballooon = [SKSpriteNode spriteNodeWithImageNamed:@"yourimagefilename"];
ballooon.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:yourSize];

ballooon.physicsBody.categoryBitMask = balloonHitCategory;
ballooon.physicsBody.contactTestBitMask = spikeHitCategory;
ballooon.physicsBody.collisionBitMask =  spikeHitCategory;

you should set your size and set your images for both of the spritenodes

SKSpriteNode *spikes = [SKSpriteNode spriteNodeWithImageNamed:@"yourimagefilename"];
spikes.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(yourSizeX, yourSizeY)];

spikes.physicsBody.categoryBitMask = spikeHitCategory;
spikes.physicsBody.contactTestBitMask = balloonHitCategory;
spikes.physicsBody.collisionBitMask =  balloonHitCategory;

for collision set up the following method:

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;

    firstBody = contact.bodyA;
    secondBody = contact.bodyB;

   if(firstBody.categoryBitMask == spikeHitCategory || secondBody.categoryBitMask == spikeHitCategory)
   {

       NSLog(@"balloon hit the spikes");
       //setup your methods and other things here 

   }
}

Before the collision will work you should also add the . In your scenes .h file add .

@interface myScene : SKScene <SKPhysicsContactDelegate>

@end

and in the .m file in the init function add:

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
    self.physicsWorld.contactDelegate = self;

    }
return self;
}

For more about collision handling check out apple documentation and adventure game example: https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/CodeExplainedAdventure/HandlingCollisions/HandlingCollisions.html#//apple_ref/doc/uid/TP40013140-CH5-SW1

I have just released a plug-in 2D collision engine for Sprite Kit. It's still in its early stages but could be of some help to you: https://github.com/henryeverett/ToastCollisions2D

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