This site requires JavaScript, please enable it in your browser!
Greenfoot back
Gamezocker
Gamezocker wrote ...

2014/3/5

Spawning from Superclass

Gamezocker Gamezocker

2014/3/5

#
Hello, I have a monster class. In it are Monster-Blue and Monster-Yellow. I want to spawn a monster from it. I would say to Java: "Spawn me an object of the superclass Monster" How have I to program it?
danpost danpost

2014/3/5

#
Gamezocker wrote...
I have a monster class. In it are Monster-Blue and Monster-Yellow. I want to spawn a monster from it.
Normally, when something is to be spawned out of thin air, it is done in the subclass of World. However, if you want to say "Monster, spawn a subclass of yourself.", this command should still originate from your subclass of World using something like 'Monster.spawnRandom(this);' and you would need to create a static method in the Monster class that randomly creates an instance of one of its subclasses and adds it to the world given in the argument of the method. A multiple 'if-else' or a 'switch' will probably need to be used within the static method to cover all possible subclass types.
davmac davmac

2014/3/5

#
I would say to Java: "Spawn me an object of the superclass Monster" How have I to program it?
Maybe I don't understand the question properly but: the same way you always do:
1
getWorld().addObject(new Monster(), x, y);
Gamezocker Gamezocker

2014/3/6

#
i have a solution for my plan:
1
2
3
4
5
6
7
8
9
int g = Greenfoot.getRandomNumber(20);
if(g == 10)
{
    getWorld().addObject(new Monster-Blue(), x, y);
}
if(g == 20)
{
    getWorld().addObject(new Monster-Yellow(), x, y);
}
danpost danpost

2014/3/7

#
Gamezocker wrote...
i have a solution for my plan:
1
2
3
4
5
6
7
8
9
int g = Greenfoot.getRandomNumber(20);
if(g == 10)
{
    getWorld().addObject(new Monster-Blue(), x, y);
}
if(g == 20)
{
    getWorld().addObject(new Monster-Yellow(), x, y);
}
'g' will never be '20'. For twenty possibilities, 'getRandomNumber' will return a number between '0' and '19' inclusive; twenty would be a twenty-first possibility.
Gamezocker Gamezocker

2014/3/7

#
ok than g = Greenfoot.getRandomNumber(21);
You need to login to post a reply.