0
我有幾個遊戲世界對象,玩家需要在他的physicsBody.categoryBitMask與他們聯繫時單獨進行交互。而不是爲每個單獨的對象使用單獨的categoryBitMasks(對象數超過categoryBitMask的限制,即32),我只使用1個categoryBitMask並給所有對象個別名稱。下面是它的外觀在代碼:訪問所有具有相同類別的單個對象BitBitMask
-(void)createCollisionAreas
{
if (_tileMap)
{
TMXObjectGroup *group = [_tileMap groupNamed:@"ContactZone"]; //Layer's name.
//Province gateway.
NSDictionary *singularObject = [group objectNamed:@"msgDifferentProvince"];
if (singularObject)
{
CGFloat x = [singularObject[@"x"] floatValue];
CGFloat y = [singularObject[@"y"] floatValue];
CGFloat w = [singularObject[@"width"] floatValue];
CGFloat h = [singularObject[@"height"] floatValue];
SKSpriteNode *object = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(w, h)];
object.name = @"provinceGateway";
object.position = CGPointMake(x + w/2, y + h/2);
object.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(w, h)];
object.physicsBody.categoryBitMask = terrainCategory;
object.physicsBody.contactTestBitMask = playerCategory;
object.physicsBody.collisionBitMask = 0;
object.physicsBody.dynamic = NO;
object.physicsBody.friction = 0;
object.hidden = YES;
[_backgroundLayer addChild:object];
}
/*More code written below. Too lazy to copy & paste it all*/
}
-(void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody, *secondBody; //Create 2 placeholder reference's for the contacting objects.
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) //If bodyA has smallest of 2 bits...
{
firstBody = contact.bodyA; //...it is then the firstBody reference [Smallest of two (category) bits.].
secondBody = contact.bodyB; //...and bodyB is then secondBody reference [Largest of two bits.].
}
else //This is the reverse of the above code (just in case so we always know what's what).
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
/**BOUNDARY contacts*/
if ((firstBody.categoryBitMask == noGoCategory) && (secondBody.categoryBitMask == playerCategory))
{
//Boundary contacted by player.
if ([_backgroundLayer childNodeWithName:@"bounds"])
{
NSLog(@"Player contacted map bounds.");
}
if ([_backgroundLayer childNodeWithName:@"nogo"])
{
NSLog(@"Player can't go further.");
}
if ([_backgroundLayer childNodeWithName:@"provinceGateway"])
{
NSLog(@"Another province is ahead. Can't go any further.");
}
if ([_backgroundLayer childNodeWithName:@"slope"])
{
NSLog(@"Player contacted a slope.");
}
}
的問題是,在didBeginContact方法,當所有的代碼被執行玩家接觸的任何對象。即使是玩家尚未聯繫的對象的代碼。這意味着IF語句(如if([_backgroundLayer childNodeWithName:@「slope」])不完整。有人可以告訴我如何正確寫出用於單個對象聯繫的IF語句嗎?
if ([_player intersectsNode:[_backgroundLayer childNodeWithName:@"slope"]])
好吧,這個工作!非常感謝你。 – Krekin
唉,這個作品如此完美我得說再次感謝你:D – Krekin
不客氣;) –