I'm trying to access an object's local variable from didBeginContact method. How's it possible ?
Let's say I've got a ball object and whenever it bounces from the player, that ball's bouncedFrom variable get's an identifier from the player.
This is my initBall method, which initialises a ball. It is called every 3-5(random) seconds.
-(void)initBall {
NSString *bouncedFrom;
bouncedFrom = @"";
ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball"];
ball.name = ballCategoryName;
ball.zPosition = 0;
int cannonPos = (arc4random() % 3 ) + 1;
SKSpriteNode *cannon = (SKSpriteNode *)[self childNodeWithName:[NSString stringWithFormat:@"%i",cannonPos]];
ball.zPosition = 3;
ball.position = cannon.position;
ball.physicsBody.categoryBitMask = ballCategory;
ball.physicsBody.contactTestBitMask = wallCategory;
ball.physicsBody.collisionBitMask = wallCategory;
ball.physicsBody.usesPreciseCollisionDetection = YES;
[self addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.frame.size.width/2];
ball.physicsBody.friction = 0.0f;
//Bounce back
ball.physicsBody.restitution = 1.0f;
//
ball.physicsBody.linearDamping = 0.0f;
ball.physicsBody.allowsRotation = NO;
switch (cannonPos) {
case 1:
ball.position = CGPointMake(ball.position.x+20, ball.position.y+20);
[ball.physicsBody applyImpulse:CGVectorMake(-1.0,1.0)];
break;
case 2:
ball.position = CGPointMake(ball.position.x-20, ball.position.y+15);
[ball.physicsBody applyImpulse:CGVectorMake(-1.0,1.0)];
break;
case 3:
ball.position = CGPointMake(ball.position.x-20, ball.position.y-15);
[ball.physicsBody applyImpulse:CGVectorMake(-1.0,-1.0)];
break;
case 4:
ball.position = CGPointMake(ball.position.x+20, ball.position.y-20);
[ball.physicsBody applyImpulse:CGVectorMake(-1.0,-1.0)];
default:
break;
}
What I want is something like this in the didBeginContact:
-(void)didBeginContact:(SKPhysicsContact *)contact {
SKPhysicsBody *firstBody;
SKPhysicsBody *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA;
secondBody = contact.bodyB;
} else {
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if ((firstBody.categoryBitMask & ballCategory) !=0) {
SKNode *ball = contact.bodyB.node;
SKNode *player = contact.bodyA.node;
ball.bouncedFrom = PlayerCategory;
}
if ((firstBody.categoryBitMask & wallCategory) !=0) {
SKNode *ball = contact.bodyB.node;
SKAction *addScore = [SKAction runBlock:^{
if (ball.position.y < 0) playerScore--;
if (ball.position.x < 0) cpu2Score--;
if (ball.position.y > self.frame.size.height) cpu1Score--;
if (ball.position.x > self.frame.size.width) cpu3Score--;
}];
SKAction *removeNode = [SKAction removeFromParent];
SKAction *sequence = [SKAction sequence:@[addScore, removeNode]];
[ball runAction:sequence];
}
}
Both ball and xCategories are declared as static variables at the top of my code. Is something like this possible ?