Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11960

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.

Upvotes: 0

Views: 3923

Answers (2)

Russell Zahniser
Russell Zahniser

Reputation: 16364

Remember that the third parameter to Rectangle is the width, not the x of the other side. So, what you really want is probably like this:

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

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

(Assuming velocity is the (positive) distance to move left or right, and only the method for the direction you are moving will be called)

Upvotes: 1

lhk
lhk

Reputation: 30256

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.

Upvotes: 1

Related Questions