0

In a game scenario, where you have an update() method is called 30 times a second, what would be the best way to do something once?

For example, if you were adding an entity into the scene:

public void update() {

    Entity e = new Entity(32, 32, true);
    e.add();

}

Because the method is being called 30 times a second, this would be adding 30 entities in one second. The way I usually do it is by creating a boolean:

private boolean entityAdded;

public void update() {

    if(!entityAdded) {
        Entity e = new Entity(32, 32, true);
        e.add();
        entityAdded = true;
    }

}

Note that this isn't specifically about adding entities, that was just an example. It could be about adding a certain amount of points to the player's score, or something.

But this seems a little messy if you have multiple cases like this, and you're creating temporary variables which can get annoying...

Is there a better way of doing this?

sparklyllama
  • 1,276
  • 4
  • 20
  • 28
  • Why are you doing something 30 times a sec. If its a specific user input that you are trying to register you could always use and eventListener (MouseListener,..) – Arno_Geismar Aug 20 '14 at 09:03
  • @Arno_Geismar This is talking about a "game scenario", where you would be updating the classes at 30 times a second or 60 times or whatever. – sparklyllama Aug 20 '14 at 09:04

3 Answers3

2

I would have a list of an action interface or you could just use Runnable.

List<Runnable> oneOffActions = new ArrayList<Runnable>();

When you decide to add a new item you add a runnable that does it.

oneOffActions.add(new Runnable(){
   @Override
   public void run(){
     Entity e = new Entity(32, 32, true);
     e.add();
   }
 });

Then you execute all the actions inside the main game loop and clear the list after.

for(Runnable runnable : oneOffActions)
   runnable.run();
oneOffActions.clear();
weston
  • 54,145
  • 21
  • 145
  • 203
1

I suggest you to store game entities in a collection like List or Map.

Map<String, Entity> entities = new HashMap<String, Entity>();

public void update() {
    if (!entities.containsKey("enemy22")) {
        entities.put("enemy22", new Entity(...))
    }
}
Alexey Odintsov
  • 1,705
  • 11
  • 13
0

You could enable Dynamic update. In wich case the update will only happen if the Entity is dirty (modified) :

@Entity
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@Table (name="Entity")
class Entity {

private int someInt;
private int anotherInt;
private boolean someBool;

public Entity(int someInt, int anotherInt, boolean someBool)
this.someInt = someInt;
this.anotherInt = anotherInt;
this.someBool = someBool;
}

you can find more elaborate information here : http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

Arno_Geismar
  • 2,296
  • 1
  • 15
  • 29