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

2016/5/12

how to get collision getOneIntersectingObject base on actual image (ignore transparent)

fandyrazzle fandyrazzle

2016/5/12

#
well hello masters of greenfoot java. i have class Amoeba (image and an Actor). I want my amoeba to eat another amoeba. Lets say we have Amoeba amoeba1=new Amoeba(); Amoeba amoeba2=new Amoeba(); So when amoeba1 and amoeba2 collide, they are united. My problem is these Amoeba collided when the square of their transparent area touched each other (I used getOneIntersectingObject). So i tried code below. But when i used these code (amoeba1 hits amoeba2):
1
2
3
4
Amoeba amoeba = (Amoeba)getOneIntersectingObject(Amoeba.class);
if (amoeba.getImage().getColorAt(getX(), getY()).getAlpha() == 0){
//action
}
the collision detected when the center of amoeba1 touched actual image of amoeba2. Do you have any idea how to detect collision of their edge of actual image, of amoeba1 hits amoeba2 (ignore both of their transparent area). Thank you my brothers.
danpost danpost

2016/5/12

#
Actually 'getOneIntersectingObject' will detect a collision when any part of its image intersect any part of the object being looked for. Using the Actor class method' getOneObjectAtOffset(0, 0, Amoeba.class) will do what you suggested the method you were using would do. There is a collision checking method in the Actor class to do what you are wanting; however, it wll list all the objects and there is no method available that will return just one of them like the other two methods above (getIntersectingObjects <> getOneIntersectingObject; getObjectsAtOffset <> getOneObjectAtOffset). The method is the 'getObjectsInRange' which does not have a compliment of 'getOneObjectInRange'. Since it return a List object (it never return a 'null value) you need to make sure that it contains at least one object before trying to acquire that object. Therefore, the code will be something like this:
1
2
3
4
5
6
int range = getImage().getWidth()/2;
if (! getObjectsInRange(range, Amoeba.class).isEmpty())
{
    Amoeba amoeba = (Amoeba)getObjectsInRange(range, Amoeba.class).get(0);
    // action
}
You can avoid calling the method twice with the following (this saves a slight bit of CPU time):
1
2
3
4
5
6
7
int range = getImage().getWidth()/2;
java.util.List amoebas = getObjectsInRange(range, Amoeba.class);
if (! amoebas.isEmpty())
{
    Amoeba amoeba = (Amoeba)amoebas.get(0);
    // action
}
You need to login to post a reply.