如何让我的应用计算此对象的次数:
- (SKNode*)addRock {
SKSpriteNode* rock = [SKSpriteNode spriteNodeWithImageNamed:@"asteroid"];
//set the position to a random X value
rock.position=CGPointMake ([self makeRandomXWBetween:0 and:self.size.width],self.size.height);
rock.name = @"rock";
rock.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:rock.size];
rock.physicsBody.usesPreciseCollisionDetection = YES;
rock.physicsBody.allowsRotation = NO;
rock.physicsBody.categoryBitMask = rockCategory;
rock.physicsBody.contactTestBitMask = dodgerCategory;
[self addChild:rock];
return self;
}
会点击此对象:
- (void)createFloor {
SKNode *floor = [SKNode node];
floor.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(CGRectGetMinY(self.frame),1.0 , CGRectGetWidth(self.frame), 1)];
floor.physicsBody.categoryBitMask = floorCategory;
[self addChild: floor];
}
基本上,我希望该应用计算“addRock”的次数。对象将与' createFloor'对象以及他们联系的次数是否可以放在左上角。
提前感谢您的帮助!
答案 0 :(得分:3)
创建一个计数器,使用didBeginContact:方法递增计数器并使用计数器更新SKLabelNode。
1)创建计数器:
@implementation MyScene
{
int counter;
BOOL updateLabel;
SKLabelNode *counterLabel;
}
-(id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
counter = 0;
updateLabel = false;
counterLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
counterLabel.name = @"myCounterLabel";
counterLabel.text = @"0";
counterLabel.fontSize = 20;
counterLabel.fontColor = [SKColor yellowColor];
counterLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
counterLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeBottom;
counterLabel.position = CGPointMake(50,50); // change x,y to location you want
counterLabel.zPosition = 900;
[self addChild: counterLabel];
}
}
2)检查联系方式:
-(void)didBeginContact:(SKPhysicsContact *)contact
{
uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
if (collision == (dodgerCategory | floorCategory))
{
counter++;
updateLabel = true;
}
}
3)更新标签文字:
-(void)update:(CFTimeInterval)currentTime
{
if(updateLabel == true)
{
counterLabel.text = [NSString stringWithFormat:@"Counter: %i",counter];
updateLabel = false;
}