Search code examples
javacollision-detection

Java Gaming collision detection, (side collision) with rectangles


I have been writing a Game Engine and I have a problem with my actor class. I want to determine the collision with a rectangle (above) and a side of a rectangle. I had written two methods for them.

public boolean isLeftCollision(Actor actor) {
    boolean bool = false;
    Rectangle LeftBounds = new Rectangle(x, y, x-velocity, image.getHeight(null));
    bool = LeftBounds.intersects(actor.getBounds());
    return bool;
}

public boolean isRightCollision(Actor actor) {
    boolean bool = false;
    Rectangle RightBounds = new Rectangle(x+image.getWidth(null), y, image.getWidth(null)+velocity, image.getHeight(null));
    bool = RightBounds.intersects(actor.getBounds());
    return bool;
}

Here velocity is the movement for next step.

But they both give me error (ie., false judgements). How can I solve this in the actor class.


Solution

  • I admit I can hardly read your code and I'm sorry if my answer isn't helpful. My guess is that the velocity in the collision produces the errors. Depending on how often you check and what values velocity holds you might register collisions that haven't occured yet...

    I'd do the collision detection in two steps.

    1. Test for a collision
    2. Determine if it's above or to one side.

    here's some pseudocode:

    Rectangle self_shape=this.getBounds();
    Rectangle other_shape=actor.getBounds();
    bool collision = self_shape.intersects(other_shape);
    if(collision){
        //create two new variables self_centerx and self_centery
        //and two new variables other_centerx and other_centery
        //let them point to the coordinates of the center of the
        //corresponding rectangle
    
        bool left=self_centerx - other_centerx<0
        bool up=self_centery - other_centery<0
    }
    

    That way you can look where the other actor is positioned relative to you. If it's above or to one side.