简体   繁体   中英

Randomly Create Enemies In Android Studio

I'm making my first android game, and i want to create a random enemy every three seconds, i have six enemies but my code it's not working!!

I don't know what i'm missing or doing wrong, i have a red line under (rand == 0) and (rand == 1) .

Please help!

The code i'm using:

if (EnemyElapsed > (2000-alien.getScore()/4)){
    switch ((int) (rand.nextDouble() * (2))) {
        if(rand == 0){
            enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.dog), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
            enemyStartTime = System.nanoTime();
        }
        else if(rand == 1){
            enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.aalien), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
            enemyStartTime = System.nanoTime();
        }
    }
}

Your problem :

rand is a Random object, you can't compare it with an int .

This is why you have the red line under (rand == 0) and (rand == 1) .


The solution :

You must use case instead of if/else blocks

if (EnemyElapsed > (2000-alien.getScore()/4)){
        switch ((int) (rand.nextDouble() * (2))) {

            case 0:
               enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.dog), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
               enemyStartTime = System.nanoTime();
            break;

            case 1:
               enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.aalien), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
               enemyStartTime = System.nanoTime();
            break;

        }
    }

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