Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Load all of your tiles into an ArrayList. Then you can use a for-each loop to apply collision detection to all of the tiles with your player. Please note that the following example may not declare everything necessary to work, but it should help you understand how this method of collision detection works and allow you to implement it into your game.</p> <p>Tile.java</p> <pre><code> import java.awt.Rectangle; private int tileWidth = 32; private int tileHeight = 32; private int x; private int y; public class Tile() { public Tile(int tx, int ty) { x = tx * tileWidth; y = ty * tileHeight; } public Rectangle getBounds() { return new Rectangle(x, y, tileWidth, tileHeight); } } </code></pre> <p>CheckCollision.java</p> <pre><code> import java.awt.Rectangle; public class CheckCollision { public boolean isColliding(Player player, Tile tile) { Rectangle pRect = player.getBounds(); Rectangle tRect = tile.getBounds(); if(pRect.intersects(tRect)) { return true; } else { return false; } } } </code></pre> <p>Player.java</p> <pre><code> import java.awt.Rectangle; import java.util.ArrayList; public class Player { public void move(ArrayList&lt;Tile&gt; tiles) { y -= directionY; //falling for(Tile t: tiles) { // for all of the Tiles in tiles, do the following Tile next = t; if(CheckCollision.isColliding(this, next) { y += directionY; //stop falling } } x -= dx; // move your x for(Tile t: tiles) { // for all of the Tiles in tiles, do the following Tile next = t; if(CheckCollision.isColliding(this, next) { x += directionY; //move back if collides } } } public Rectangle getBounds() { return new Rectangle(playerX, playerY, playerWidth, playerHeight); } } </code></pre> <p>Graphics.java (Your class that draws the tiles and player)</p> <pre><code> import java.awt.ActionListener; import java.util.ArrayList; public class Graphics extends JPanel implements ActionListener { public ArrayList&lt;Tile&gt; tiles = new ArrayList(); Player player = new Player(); public JPanel() { tiles.add(new Tile(0, 0)); //adds a Tile at X:0 Y:0 to ArrayList tiles } @Override public void ActionPerformed(ActionEvent e) { player.move(tiles); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload