File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make enemy only spawn once?

 
Natasha Morehouse
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am making a java game and I need to only spawn the boss once, but I am not sure how to do this.

Here is the code I have to spawn the boss:

else if (level==5)
{
double xPosition = random(0, pfWidth());
new EnemyBoss(xPosition, 100.0);
}
 
Manuel Petermann
Ranch Hand
Posts: 177
Hibernate Linux Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think we might need a bit more context to help you.
If your code does what i think it does (and whithout having a look at the constructor of the EnemyBoss i cant be sure) your mistakes is not within those lines.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look up the singleton pattern. People used to think singletons were really good things, but opinion has changed and some people say singletons are evil. It might be appropriate to make your boss a singleton. That would mean you can get as many references to the boss object as you like; they will all point to the same object.
 
Winston Gutkowski
Bartender
Pie
Posts: 9469
49
Eclipse IDE Hibernate Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Natasha Morehouse wrote:Here is the code I have to spawn the boss:

Which looks like it will spawn a boss (whatever that means) whenever you reach level 5. I'm not quite sure if I agree with Campbell's advice about making it a singleton (although I definitely agree with him that they're worth knowing about), but you do need to record somewhere that you've already spawned a boss.
Then your code might look something like:Winston
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote: . . . I'm not quite sure if I agree with Campbell's advice about making it a singleton . . .
Nor am I. I was offering it as a suggestion rather than advice.
An alternative is to have a static count variable in the Boss class; you only instantiate the class if it is 0. If you are multi‑threading, that method can allow several Boss objects to exist, if the constructor is accessed simultaneously by several threads. Again just a suggestion, rather than advice.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic