How to detect collisions using Slick2D?

1

I would like to know how I can detect collisions between objects using slick, do you have any useful examples?

I'm playing a simple game where 2 squares are moving on the screen and if the character I'm moving through the keyboard is hit by some of the squares, it goes back to the beginning of the phase

    
asked by anonymous 29.01.2014 / 21:43

1 answer

1

You must associate a variable of type Rectangle with objects that will detect a collision (it is part of Slick2D). When building a Rectangle, the x, y, width, and height parameters must be given, and whenever that object moves, you must use setBounds to update those values. As Rectangle extends Shape, you can use the intersects method of the Rectangle variable by passing another Shape (in this case, the rectangle of the other potentially colliding object) and using the boolean returned to do any processing based on that event.

An example:

if (objectA.getRectangle().intersects(objectB.getRectangle())) {
  System.out.println("Colisao detectada");
}

Where objectA and objectB are objects of your game, which have position and a Rectangle (or any other Shape available in Slick2D) to be used as a collision box. Collision processing depends on the type of game being played. Normally, we do not allow movement to occur if it causes a collision.

Slick2D Rectangle class documentation: link

    
29.01.2014 / 21:58