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

2023/3/19

I need an actor to follow an other actor

gijsdevries gijsdevries

2023/3/19

#
I am making a game where a certain class of actors need to follow an other actor from a different class. What I have now works fine but when a monster eats a player I get a terminal window. The terminal window says there is a problem with rule 17 and 22. Does anyone one how I can get rid of the terminal window? here is my code
public class Monsters extends Actor
{
    /**
     * Act - do whatever the Monsters wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        // Add your action code here.
    }
    public void doeMonsterDingen() {
        if (Player.class != null) {
        move(4);
        Actor player = getWorld().getObjects(Player.class).get(0);
        turnTowards(player.getX(), player.getY());
        }
    }
    public void turnRandom (int maxDegree) {
        if (maxDegree > 0) {
            turn(Greenfoot.getRandomNumber(2*maxDegree) - (maxDegree));
        }
    }
    public void eetSpeler() {
        if (isTouching (Player.class)) {
            removeTouching(Player.class);
            Greenfoot.playSound ("eat.wav"); 
        }
    }
    public void loopNietDoorSteen() {
        if (isTouching (Obstakels.class)) {
            turnRandom(90);
        }
    }
}
Spock47 Spock47

2023/3/20

#
The given line numbers (17 and 22) are not accurate regarding the shown source code: maybe because the imports have been left out; maybe you also removed the call of the helper methods from the act method (currently it is empty)? However, the problem is that "doing something with the first player" will fail if there is no player in the world, i.e. "getWorld().getObjects(Player.class)" will be an empty list if there is no player. Therefore, one should not ask for the first entry of this list in this case. The solution is to ensure that the list is not empty before proceeding:
        final List<Player> players = getWorld().getObjects(Player.class);
        if (!players.isEmpty()) {
            final Actor player = players.get(0);
            turnTowards(player.getX(), player.getY());
            move(4);
        }
Live long and prosper, Spock47
danpost danpost

2023/3/20

#
gijsdevries wrote...
if (Player.class != null) {
The condition here will ALWAYS be true (if you have a class called Player).
You need to login to post a reply.