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

2014/11/13

Checking Other coordinates

Hersov Hersov

2014/11/13

#
Hey guys, im making a basic program with 2 actors who each move to the right every time they are clicked, I was wondering if there was anyway for one to check the others location and act accordingly to where it is, for instance . I know I can use if and else but is there any way to find the other actor inside of this actor class?
davmac davmac

2014/11/13

#
The best way is to have an instance variable which holds a reference to the other actor. You need to set it after creating both actors. Eg:
1
2
// in the actor
public ActorType otherActor;
and
1
2
3
4
5
// in the world, or wherever you create the actors:
ActorType a1 = new ActorType();
ActorType a2 = new ActorType();
a1.otherActor = a2;
a2.otherActor = a1;
and, in the actor, when you want to use the position of the other actor:
1
2
3
4
5
int otherX = otherActor.getX();
int otherY = otherActor.getY();
if (otherX == 10 && otherY == 10) {
   // eg do something!
}
Hersov Hersov

2014/11/17

#
Ok thank you but Is there a way to check the coordinate instead of the actor, for instance if i was to check a coordinate to something like if (otherX == 0 && otherY == 7) !=null, move (0) (I know this code is really sketchy but I hope you see what im trying to say). So if i was trying to say that the coordinate 0,7 is occupied then do this, and then ill do an else statment if its not occupied, Im doing this still with my dolphin and bee code so I want the dolphin to detect if the coordinate is occupied by the bee and then move (0) instead of move(1). Thanks alot for you help
davmac davmac

2014/11/17

#
I know this code is really sketchy but I hope you see what im trying to say
I'm not certain that I do, to be honest.
if i was to check a coordinate to something like if (otherX == 0 && otherY == 7) !=null, move (0)
You can use the world's getObjectsAt(...) method to check if there are any actors at specified co-ordinates. (It returns a list, so use 'isEmpty()' on the result to check whether there were any actors found.) If you have a reference to another actor and want to check if any other actor occupies the same location, you can use getOneObjectAtOffset() or any of the collision checking methods if appropriate.
danpost danpost

2014/11/17

#
You can also go ahead and let the actor move(1) and then check for the other one using 'getOneIntersectingActor' (returning an Actor object or 'null') or 'getIntersectingObjects' (returning a List object). If the one is not 'null' or the other is not empty, just execute move(-1), which then has a move sum equivalent to move(0) (if all done in the same block of code).
You need to login to post a reply.