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

2012/6/10

Actor locating other Actor positions.

gusbus123 gusbus123

2012/6/10

#
Hi i've been having real trouble lately about trying to make a part of a pacman game. In this problem there is 3 main classes involved. Ghost1, Player, Food1. I am trying to have a code from the Ghost1 actor that locates each Food1 and check if the Player is on the exact same position as the food. Is there a way to do this?
danpost danpost

2012/6/10

#
To get the Food1 obect that is the Player is currently on, use this call with the following method:
Food1 eating = getCurrentFood();
if (eating != null) ...
private Food1 getCurrentFood()
{
    for (Object obj : getWorld().getObjects(Food1.class))
    {
        Food1 food = (Food1) obj;
        if (!food.getIntersectingObject(Player.class).isEmpty()) return food;
    }
    return null;
}
However, the code for the Player must eat first, then move (it cannot move first, then eat; because, then, the Ghost1 object will always have null returned by the method).
gusbus123 gusbus123

2012/6/10

#
k i will try that now.
gusbus123 gusbus123

2012/6/10

#
private Food1 getCurrentFood()
{
    for (Object obj : getWorld().getObjects(Food1.class))
    {
        Food1 food = (Food1) obj;
        if (!food.getIntersectingObject(Player.class).isEmpty()) return food;
    }
    return null;
}
For this part it gave an error that it couldnt find the symbol of the "getIntersectingObject" bit.
MatheMagician MatheMagician

2012/6/11

#
I believe it is getIntersectingObjects() not Object(). Also, you might want to import java.util.*
gusbus123 gusbus123

2012/6/11

#
k thx
gusbus123 gusbus123

2012/6/11

#
it now says "getIntersectingObjects(java.lang.Class) has protected access in greenfoot.Actor". i had the import done in the beginning so i dont kno y its saying its still protected.
danpost danpost

2012/6/11

#
The import is not neccessary. I'll check into the protection thing.
gusbus123 gusbus123

2012/6/11

#
k thx
danpost danpost

2012/6/11

#
Alright, I guess we will have to add a method the the Food1 class to get the intersecting player state. In the Food1 class, add this method:
public boolean hasPlayer()
{
    return !getIntersectingObjects(Player.class).isEmpty();
}
and in the Ghost1 class, change the getCurrentFood() method to:
private Food1 getCurrentFood()
{
    for (Object obj : getWorld().getObjects(Food1.class))
    {
        Food1 food = (Food1) obj;
        if (food.hasPlayer()) return food;
    }
    return null;
}
gusbus123 gusbus123

2012/6/11

#
YES!!! thx guys got it to work.
You need to login to post a reply.