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

2015/12/23

Randomly moving enemy problem

Arakniode Arakniode

2015/12/23

#
Hello, I am a beginner with java in general, and I'm currently trying to create a randomly moving actor from the class "Crab" but I'm having some issues. I only want it to move up/down/left/right, and the problem is that it is only moving in one direction and not stopping until it touches the borders of the world. Here's my code for the "Crab" class:
public void act() 
    {
        int crabmovechoice = (Greenfoot.getRandomNumber(4));
        switch (crabmovechoice)
        {
            case 1:
                move(30);
                crabmovechoice = (Greenfoot.getRandomNumber(4));
            case 2:
                move(-30);
                crabmovechoice = (Greenfoot.getRandomNumber(4));
            case 3:
                setLocation(getX(),getY()-30);
                crabmovechoice = (Greenfoot.getRandomNumber(4));
            case 4:
                setLocation(getX(),getY()+30);
                crabmovechoice = (Greenfoot.getRandomNumber(4));
        }
Thank you in advance for your help :)
Arakniode Arakniode

2015/12/23

#
I now understood the problem, I have to put a "break;" statement at the end of each case, and remove the "crabmovechoice = (Greenfoot.getRandomNumber(4));". Also, it gives a number between 0 and 3.
fejfo fejfo

2015/12/23

#
this still won't work really well beacause the crab will move back and forth a lot code like this would be better :
int targetX = getX();
int targetY = getY();
public void act() {
   if(getX() == targetX && getY() == targetY) {    
      int targetX = Greenfoot.getRandomNumber(getWorld().getWidth());
       int targetY = Greenfoot.getRandomNumber(getWorld().getHeight());
        turnTowards(targetX,targetY);
   }
   move(30);
}
You need to login to post a reply.