How to detect collisions using Slick2d?

Asked

Viewed 286 times

1

I would like to know how I can detect collisions between objects using Slick,have some useful example?

I’m making a simple little game where 2 squares are moving on the screen and if the character I’m moving around the keyboard is hit by any of the squares, it goes back to the beginning of the stage

  • Hello, welcome to Stackoverflow in English. Your question is a little general and so it is difficult to help. Would it be possible to improve it a little? For example, adding information about what you’ve tried, or what kind of objects (are images?) you’re using?

1 answer

1

You need to associate with the objects that will detect collision a Rectangle type variable (it is part of Slick2d). When constructing a Rectangle, the parameters x, y, width and height should be given and whenever this object moves, you should use setBounds to update such values. As Rectangle extende Shape, you can use the Rectangle variable Intersects method by passing another Shape (in this case, the Rectangle of the other object that potentially collides) and using the returned Boolean to do any processing based on that event.

An example:

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

Where object and objectB are objects of your game, which have a position and a Rectangle (or any other Shape available on Slick2d) to be used as a collision box. The processing of the collision 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: http://slick.ninjacave.com/javadoc/org/newdawn/slick/geom/Rectangle.html

  • Thanks Thiago I will try this vlw

  • 1

    If my answer has been helpful do not forget to accept it. Good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.