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

2013/2/10

Help with collission

FergisonSan FergisonSan

2013/2/10

#
Hey Guys, I'm having a problem by preventing my actors from hitting each other. I want them to turn before they are onto another actor but i can't manage to make them do so. Might getIntersectingObjects help and if yes how do I use it right. Thanks for your time :)
Gevater_Tod4711 Gevater_Tod4711

2013/2/10

#
If you use getIntersectingObjects your actors will turn when they hit each other. If you want them to change the direction before they hit each other this would be more complicated. Using getIntersectingObjects it should work like this:
//first you have to import java.util.List;

//in your act method;
List<Actor> intersectingActors = getIntersectingObjects(Actor.class);//if you just want to check whether there is a specific class you can use this class instead of Actor;
if (!intersectingActors.isEmpty()) {
    for (Actor actor : intersectingActors) {
        actor.setRotation(directionToTurnTo(actor.getX(), actor.getY()));
    this.setRotation(directionToTurnTo(actor.getX(), actor.getY()) + 180);
    }
}

//also you need this methods:
    public int directionToTurnTo(int x, int y) {
        return direction(x - getX(), y - getY());
    }
    
    public int direction(int deltaX, int deltaY) {
        int direction;
        if(deltaX == 0 && deltaY == 0) {
            direction = 0;
        }
        else if(deltaX == 0 && deltaY < 0) {
            direction = -90;
        }
        else if(deltaX == 0 && deltaY > 0) {
            direction = 90;
        }
        else if(deltaX > 0 && deltaY == 0) {
            direction = 0;
        }
        else if(deltaX < 0 && deltaY == 0) {
            direction = 180;
        }
        else {
            int w = (int) Math.toDegrees(Math.atan((double)deltaY / (double)deltaX));
            if(deltaX > 0) {
                direction = w;
            }
            else {
                direction = 180 + w;
            }
        }
        return direction;
    }
Using this code your actors will move away from each other when they hit each other.
FergisonSan FergisonSan

2013/2/10

#
The actor is still onto the other one before the turns
FergisonSan FergisonSan

2013/2/10

#
Also it just works one time.
Gevater_Tod4711 Gevater_Tod4711

2013/2/11

#
You could try to use getObjectsInRange(); Then the actors might change their direction before they crash. Change line 4 of the code I postet before to this:
List<Actor> intersectingActors = getObjectsInRange(getImage().getWidth()*2, Actor.class);
You need to login to post a reply.