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

2013/12/13

GetObjectsInRange Need help!

Rickboy26 Rickboy26

2013/12/13

#
So i´m trying to let the enemy follow the hero when he´s in range of him. But i don´t have a clue on how to do this. Can somebody help me. Enemy name = Gnomus Hero name = Garp Gnomus Follows garp in certrain range.
Zamoht Zamoht

2013/12/13

#
In the act method of the enemy class.
public void act()
{
    Garp garp = getObjectsInRange(range, Garp.class).get(0);
    if (garp != null) {
        turnTowards(garp.getX(), garp.getY());
        move(movespeed);
    }
}
You may need to import java.util.List The code is not tested but should work. 'range' is a radius you decide. 'movespeed' is the amount of pixels the enemy will move every act.
davmac davmac

2013/12/13

#
Zamoht:
    Garp garp = getObjectsInRange(range, Garp.class).get(0);
... will throw an exception if the list returned by getObjectsInRange(...) is empty.
danpost danpost

2013/12/13

#
Also (after doing the correction that davmac inferred), the expression on the right cannot be set to the field declared on the left because an Actor is not necessarily a Garp. You need to cast the right side to be of Garp type or change the type on the field on the left to be of Actor type.
Zamoht Zamoht

2013/12/14

#
Yeah mistakes were made. I think the code should look like this with your guys corrections:
public void act()  
{  
    List garpList = getObjectsInRange(range, Garp.class);
    if (!garpList.isEmpty()) {
        Garp garp = (Garp)garpList.get(0);
        if (garp != null) {  
            turnTowards(garp.getX(), garp.getY());  
            move(movespeed);  
        }  
    }
}  
Please correct me again if I'm wrong. I know the 'null check' shouldn't really be necessary, but I chose to just leave it there.
You need to login to post a reply.