Skip to main content

Java 2D Tile Collision

I have been working on a way to do collision detection forever, and just can't figure it out. Here's my simple 2D array:

for (int x = 0; x < 16; x++) {
           for (int y = 0; y < 16; y++) {
              map[x][y] = AIR; 
              if(map[x][y] == AIR) {
                 air.draw(x * tilesize, y * tilesize);
                 
              }
              
           }
        }
    
    for (int x = 0; x < 16; x++) {
           for (int y = 6; y < 16; y++) {
              map[x][y] = GRASS; 
              if(map[x][y] == GRASS) {
                 grass.draw(x * tilesize, y * tilesize);
                 
              }
              
           }
        }
    for (int x = 0; x < 16; x++) {
           for (int y = 8; y < 16; y++) {
              map[x][y] = STONE; 
              if(map[x][y] == STONE) {
                 stone.draw(x * tilesize, y * tilesize);
              }
              
           }
        }

I want to do it with rectangles, and using the intersect() method, but how would I go about adding rectangles to all the tiles?

Edit:

My player moves like this:

if(input.isKeyDown(Input.KEY_W))
    {
        shiftY -= delta * speed;
        idY = (int) shiftY;
        
        if(shift == true)
        {
            shiftY -= delta * runspeed;
        }
        
        if(isColliding == true)
        {
            shiftY += delta * speed;
        }
    }
    
    if(input.isKeyDown(Input.KEY_S))
    {
        shiftY += delta * speed;
        idY = (int) shiftY;
        
        if(shift == true)
        {
            shiftY += delta * runspeed;
        }
        
        if(isColliding == true)
        {
            shiftY -= delta * speed;
        }
    }
    
    if (input.isKeyDown(Input.KEY_A)) {
        steve = left;
        shiftX -= delta * speed;
        idX = (int) shiftX;
        
        if(shift == true)
        {
            shiftX -= delta * runspeed;
        }
        
        if(isColliding == true)
        {
            shiftX += delta * speed;
        }
    }

    if (input.isKeyDown(Input.KEY_D)) {
        steve = right;
        shiftX += delta * speed;
        idX = (int) shiftX;
        
        if(shift == true)
        {
            shiftX += delta * runspeed;
        }
        
        if(isColliding == true)
        {
            shiftX -= delta * speed;
        }
    }

(I have tried my own collision code, but its horrible. Doesn't work in the slightest)

user20439