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

2014/3/15

Using getObjectsAtOffset to check for other objects in front or behind

blorange2 blorange2

2014/3/15

#
I am trying to use getObjectsAtOffset in order to check if there is an Actor at a certain distance from another. Consider this diagram - Object 1 ----------- 80 pixels ------------ Object 2. If the object is near object 2 I want it to stop until Object 2 is further away.
danpost danpost

2014/3/15

#
I will presume that the cellsize of your world is one. Please confirm this. Also, how do Object1 and Object2 move. That is, four-way movement (North, South, East and West), eight-way movement (N, NE, E, SE, S, SW, W, NW) or universal (along any angle -- usually the direction the object is facing).
blorange2 blorange2

2014/3/15

#
The objects move by use of the Greenfoot move() method (in the direction they are facing). Each cell is indeed 1 pixel, my world is 800 x 600 x 1. Basically the objects move from bottom to top and left to right... What i need is them to know if an object is within a certain distance in front. I could use getObjectsInRange() but i only need to know if there is an object directly in front, within a certain distance.... I tried the following...
List inFront = getObjectsAtOffset(getImage.getHeight() + (distance from object));
if(inFront != null){
    // do something
}
However I am not sure whether this is fully correct?
danpost danpost

2014/3/15

#
Using getObjectsAtOffset is out of the question. If your actor can be facing any direction, the horizontal axis and vertical axis will not align with the direction the actor is looking and the offsets used in the method will not (unless the rotation of your actor happens to be zero) refer to the same location that you want to look at. There are two ways I can immediately think to do this: (1) have your actor personally inspect the area ahead
move(80);
boolean okToMove = getIntersectingObjects(null).isEmpty();
move(-80);
if (okToMove) move(5);
If you have some actors that may be skipped over, this could be done in two or more steps.
move(40);
boolean okToMove = getIntersectingObjects(null).isEmpty();
move(40);
okToMove = okToMove && getIntersectingObjects(null).isEmpty();
move(-80);
if (okToMove) move(5);
(2) add a temporary object into the world covering the area that needs to be clear, call a method within its class to return whether it is clear or not (it has no intersecting objects other than maybe the object1 actor), remove the actor and move if the area was empty of other actors. The second way has the added benefit of checking an entire area instead of one or more point along a line.
You need to login to post a reply.