1

我正在制作一个仅用于测试一些代码的应用程序。有一艘正在射击敌人的船。这些敌人从屏幕顶部下来并被添加了这个代码(它的4个不同的敌人的原因是他们都有不同的行为)

-(void) addEnemy {   

int randomX = arc4random() % screenWidth; 

Enemy* anEnemy;

int diceRoll = arc4random() % 4; 

if (diceRoll == 0) {
    anEnemy = [Enemy createEnemy:@"enemy1" framesToAnimate:24];

} else if (diceRoll == 1) {
    anEnemy = [Enemy createEnemy:@"enemy2" framesToAnimate:17];

} else if (diceRoll == 2) {
    anEnemy = [Enemy createEnemy:@"enemy3" framesToAnimate:14];

} else if (diceRoll == 3) {

    anEnemy = [Enemy createEnemy:@"enemy4" framesToAnimate:24];
}

[self addChild:anEnemy z:depthLevelBelowBullet];
anEnemy.position = ccp ( randomX , screenHeight + 200);

numberOfEnemiesOnstage ++; 
}

敌人被添加了一个随机的 x 值,这意味着敌人有时在屏幕之外的一半。像这样:

如何限制屏幕两侧的 x 值,以免发生这种情况?

4

2 回答 2

2

You're not considering the image width when you're calculating the random x position. You have to move the randomX declaration and initialization after you've created the enemy objects so the textureRect property will be properly set.

int offset = (int)[Enemy textureRect].size.width / 2;
int randomX = (arc4random() % (screenWidth - (2 * offset))) + offset;
于 2013-03-02T17:27:34.423 回答
0

上面的答案是正确的,但如果你使用的是 CCSprite,它会有点不同。试试下面的代码:

-(void) addEnemy {   

int randomX = arc4random() % screenWidth; 

Enemy* anEnemy;

int diceRoll = arc4random() % 4; 
int halfWidth;

if (diceRoll == 0) {
    anEnemy = [Enemy createEnemy:@"enemy1" framesToAnimate:24];
    halfWidth = anEnemy.contentSize.width/2;

} else if (diceRoll == 1) {
    anEnemy = [Enemy createEnemy:@"enemy2" framesToAnimate:17];
    halfWidth = anEnemy.contentSize.width/2;

} else if (diceRoll == 2) {
    anEnemy = [Enemy createEnemy:@"enemy3" framesToAnimate:14];
    halfWidth = anEnemy.contentSize.width/2;

} else if (diceRoll == 3) {

    anEnemy = [Enemy createEnemy:@"enemy4" framesToAnimate:24];
    halfWidth = anEnemy.contentSize.width/2;
}

if(randomX < halfWidth) {
    randomX = halfWidth;
} else {
    randomX = randomX-halfWidth;
}

[self addChild:anEnemy z:depthLevelBelowBullet];
anEnemy.position = ccp ( randomX , screenHeight + 200);

numberOfEnemiesOnstage ++; 
}
于 2013-03-02T17:58:33.387 回答