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

2017/10/3

I'm all new. I want to know on how to make an object chase another? So this is what i got so far.

HolkyRocky HolkyRocky

2017/10/3

#
public void Chaser()
    {
        List<Fishes> fishes = (List<Fishes>) getObjectsInRange(3000, Fishes.class);
        
        if(!fishes.isEmpty())
        {
            move(-10);
            Fishes chase = fishes.get(4);
            turnTowards(chase.getX(), chase.getY());
            
        }
        
    }
danpost danpost

2017/10/3

#
If it is possible that there are no fish, then it is possible to have just one, or two, or three, or four. It is not definite that five are in the world when line 8 is executed. Line 5 only guarantees that there is at least one fish in the world. Either change '4' in line 8 to '0' or change line 5 to check the size of the list instead of checking the state of it being empty. I cannot say whether a particular fish will be "locked on" or not. It may very well be that the chaser may change targets in mid-stream (even possibly to another fish that is further away than the one it was initially chasing. You may want to iterate through the list of fish to target the closest one; then, keep a reference on that particular one -- only changing it when (a) it gets out of range; (b) it gets eaten; (c) another one gets closer; or (d) it is no longer in the world.
You need to login to post a reply.