Question

I am building a simple game in SpriteKit where the player controls a ball using the accelerometer in order to catch different powerups , coins , whatever . The problem is that when calling the method (generatePowerUp) responsible with generating a random new powerup(node) it always creates a new one at (0,0) coordinates . Same method called anywhere else works fine .

- (void)generatePowerUp {
CGPoint newPoint = CGPointMake([self randomFloatBetween:30 and:290], [self randomFloatBetween:30 and:450]);
powerUp = [SKSpriteNode spriteNodeWithImageNamed:@"me"];
powerUp.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.powerUp.size.width/2];
powerUp.physicsBody.categoryBitMask = powerUpCategory;
powerUp.position = newPoint;
powerUp.physicsBody.contactTestBitMask = playerCategory;
[self addChild:powerUp];

}

-(void)didBeginContact:(SKPhysicsContact *)contact{

if (contact.bodyA.categoryBitMask == powerUpCategory) {
    [contact.bodyA.node removeFromParent];
    myScore++;
    [self generatePowerUp];

}
if (contact.bodyB.categoryBitMask == powerUpCategory) {
    [contact.bodyB.node removeFromParent];
    myScore++;
    [self generatePowerUp];
}
}

Any ideas why this happens? I used nslog to check the random points created and there is no problem there .

Was it helpful?

Solution

Set the coordinates BEFORE creating physics body. Setting coordinates on an object that has physics body provides undefined results.

Why? Because when using physics we let physics engine determine position of all objects with physics bodies. So setting new position doesn't have much effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top