Search code examples
javacollision-detectionspritegame-physics

How do I make a solid rectangle in Java?


How do I make a solid rectangle (or block) in java so my player can stand on it?

At the moment I am saving the last position, and once I detect the player's rectangle and the block's rectangle intersect...I reset the position to the previous one. But that doesn't work out well.

Is there a better way?


Solution

  • You're asking, in a sense, how to implement some of the first basics of a two-dimensional Physics Engine.

    Note that even large game studios are using engines others have built...big names like Halo, Bioshock, Assassin's Creed etc. all use "Havok":

    http://en.wikipedia.org/wiki/Havok_(software)

    Even in the much simpler world of 2-D platformers, it might be better to start from a bit of higher level stuff. You accept that you've been given a routine to draw rectangles and circles (instead of plotting pixels out by yourself). Why not let yourself use a sprite library someone's already made?

    If you want to work with more basic physics and algorithms, there's also the likes of JBox2D, which can be fun:

    http://www.jbox2d.org/

    Beyond that, the answers to the following question might be useful, including some leads to platformer libraries:

    Collision Detection between two images in Java

    I'll also add that sometimes if you are trying to come up with a game, it can be more important to prototype and prove that your design is actually fun before going through all the trouble of writing it. Some good tools out there for that, but GameSalad is a big one I'm hearing about lately. Other resources:

    http://en.wikipedia.org/wiki/Category:Video_game_creation_software