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

2012/7/9

How Do I get one object to follow another?

EpicAlbino EpicAlbino

2012/7/9

#
Specifically, I am trying to make a Zombie Game. I want Zombies to follow the person around. This is my source, any Help is appreciated. Thanks public void act() { moveIt(); followHuman(); RandMove(); } public void moveIt() { move(2); if(atWorldEdge()) { turn(5); } } public void RandMove() { if(Greenfoot.getRandomNumber(100)>20) { turn(Greenfoot.getRandomNumber(20)-10); } } public void followHuman() { String target; getObjectsInRange(400,Survivor.class); int targetX = getX(); int targetY = getY(); }
danpost danpost

2012/7/9

#
The Actor class has a 'turnTowards(int x, int y)' method, but you need Greenfoot 2.2.0 or better to use it. Check out the Documentation.
MatheMagician MatheMagician

2012/7/9

#
You also will have to modify followHuman() so you can get the x and y location of the survivor. The altered follow human would look like:
public void followHuman()
    {
        String target;
        
        List<Survivor> group = getObjectsInRange(400,Survivor.class);
          if(group.size()>0){
                  Actor guy = group.get(0);
                  int targetX = guy.getX();
                  int targetY = guy.getY();
                  turnTowards(targetX,targetY);
              }   
 }
EpicAlbino EpicAlbino

2012/7/9

#
@MatheMagician, thanks a ton. That really Helped out, expect to see zombies coming out soon!
MatheMagician MatheMagician

2012/7/9

#
I will be watching.
-nic- -nic-

2012/11/18

#
How would you adapt the code so if another object comes closer it turns to that insted?
danpost danpost

2012/11/18

#
To follow the closest object:
public void followHuman()
{
    int dist = 400;
    Actor closest = null;
    if(!getObjectsInRange(dist, Survivor.class).isEmpty())
    {
        for (Object obj: getObjectsInRange(dist, Survivor.class))
        {
            Actor guy = (Actor) obj;
            int guyDist = Math.hypot(guy.getX() - getX(), guy.getY() - getY());
            if (closest == null || guyDist< dist)
            {
                closest = guy;
                dist = guyDist;
            }
        }
        turnTowards(closest.getX(),closest.getY());
    }   
}
-nic- -nic-

2012/11/18

#
ive got a error : possible loss of precision found double required int
danpost danpost

2012/11/18

#
Sorry, change line 10 in my above post to
int guyDist = (int) Math.hypot(guy.getX() - getX(), guy.getY() - getY());
-nic- -nic-

2012/11/18

#
thanks and thanks for replying so quick
You need to login to post a reply.