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

2013/5/15

A method, that affects all objects of a class

Maddin Maddin

2013/5/15

#
I'm currently working on my game: http://www.greenfoot.org/scenarios/8167 and i have a question: Is it possible to programm, that if an enemy gets me, every enemy will stop moving an jump (for example). Thanks in advantage :)
Gevater_Tod4711 Gevater_Tod4711

2013/5/15

#
To get all instances of the class enemy you just have to use this:
//first you have to implement this:
import java.util.List;

public void allertAllEnemys() {
    List<Enemy> enemys = getWorld().getObjects(Enemy.class);
    if (enemys != null && !enemys.isEmpty()) {
        for (Enemy enemy : enemys) {
            enemy.jump();//or any other mehtod;
        }
    }
}
If your enemy class is not called Enemy you will have to change that (List<Enemy>, getObjects(Enemy.class), ...) This method will call the method you want to execute in every instance of the class enemy that is in your world.
Maddin Maddin

2013/5/15

#
Thanks, i'll try :D
Maddin Maddin

2013/5/15

#
And can i also set an int like 'speed' for every enemy? EDIT: Doesn't work it says 'cant find method "jump()" but i have it..
Gevater_Tod4711 Gevater_Tod4711

2013/5/15

#
You have to declare the method jump in your enemy class. Otherwhile you can't execute it. And of course you can set an int in every object. You just have to declare a method in your enemy that sets this int. Like this:
//in your enemy class;
private int speed;

public void jump() {
    //let your enemy jump;
}

public void incrementSpeed(int speed) {
    this.speed = speed;
}
Then you just have to change the method call of your enemy. Instead of enemy.jump() you use enemy.setSpeed(5); //or any other value;
Maddin Maddin

2013/5/15

#
OK, fixed the problem, one last question can i set the int from an other class with this?
Gevater_Tod4711 Gevater_Tod4711

2013/5/15

#
Of course you can. From every class you want. And also for every class you want (not only enemy).
Maddin Maddin

2013/5/15

#
Ok thanks, gives me a lot of possibilities :DD
You need to login to post a reply.