简体   繁体   English

SpriteKit-生成随机节点

[英]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 . 我正在SpriteKit中构建一个简单的游戏,玩家使用加速度计控制球,以便捕捉不同的能量道具,硬币等。 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 . 问题在于,当调用负责生成随机新powerup(node)的方法(generatePowerUp)时,它总是在(0,0)坐标处创建一个新的。 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 . 我使用nslog检查创建的随机点,那里没有问题。

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. 因此,设置新职位不会产生太大影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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