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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…