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

2017/11/25

How do I make one object detect whether or not there is another object nearby?

katolop katolop

2017/11/25

#
I'm trying to make a game where if a horse detects there is an apple within 50 cells, then it will eat it. I tried to use the getObjectsInRange method, but it said I couldn't use it since the return type was a protected ArrayList. Is there another way to do this?
Super_Hippo Super_Hippo

2017/11/25

#
How did you try to use it?
danpost danpost

2017/11/25

#
The return type is an ArrayList -- but it is not what is protected. The method, 'getObjectsInRange' is what is protected. As such, you can only get the objects in range of an actor (like the horse) from the class (or subclass) of the actor (horse). It is a behavior of a horse to eat and, therefore, the method that has a horse eat should be in the class of the horse:
public void eatAnApple()
{
    if ( ! getObjectsInRange(50, Apple.class).isEmpty() )
    {
        getWorld().removeObject((Actor)getObjectsInRange(50, Apple.class).get(0));
        applesEaten++; // or whatever else you do when an apple is eaten
    }
}
katolop katolop

2017/11/25

#
For some reason, I am getting an IndexOutOfBoundsException Error. Isn't the if statement suppose to handle that?
Super_Hippo Super_Hippo

2017/11/25

#
Is it pointing to that line? Show the code of the whole class.
katolop katolop

2017/11/26

#
    public void turn(){
        List list = getObjectsInRange(50,Apple.class);
        int x = getObjectsInRange(50,Apple.class).get(0).getX();
        int y = getObjectsInRange(50,Apple.class).get(0).getY();
        if(list.size()  > 0){
            turnTowards(x,y);
        }
        else{
            move(100);
        }
    }
This gives me the IndexOutOfBoundsException
danpost danpost

2017/11/26

#
You cannot execute lines 3 and 4 with out first asking what is on line 5.
katolop katolop

2017/11/26

#
Thank you so much!
You need to login to post a reply.