简体   繁体   中英

SpriteKit - Generating random nodes

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM