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

2016/9/28

How do I get one object to follow another?

TheMemeMan TheMemeMan

2016/9/28

#
I am quite new to Greenfoot and I am trying to make a zombie game where the player(s) have to survive for as long as possible. I have it so that the zombies switch to the other side of the screen upon touching the border but as well as this I would like my zombie horde to follow the player(s) as well as not overlap with other zombie sprites. Any help would be much appreciated and please try to explain to me in basic terms :). The following is the code for my zombie....
  public void act() 
    {
       move(1);
       if (getX()< 10 || getX()>1590){
           setLocation(Greenfoot.getRandomNumber(11), Greenfoot.getRandomNumber(710));
    }
      if (getY()< 10 || getY()>700){
           setLocation(Greenfoot.getRandomNumber(11), Greenfoot.getRandomNumber(710));
    }
    
    Actor collide;
    collide = getOneIntersectingObject(Player_1.class);
    if (collide !=null){
        getWorld().removeObject(collide);
    }
    collide = getOneIntersectingObject(Player_2.class);
    if (collide !=null){
        getWorld().removeObject(collide);
    }
}
}
Super_Hippo Super_Hippo

2016/9/29

#
Well, right now, it it does not really switch to the other side. To let them turn to the player, you can use the 'turnTowards' method. To make it work, you need a reference to the player objects. And you need some rule to decide which player to follow if there are two. To stop them from overlapping, check for intersecting between zombies after they moved and then, move back if they moved on another zombie.
You need to login to post a reply.