Java 2D Tile Collision

Posted by opiop65 on Game Development See other posts from Game Development or by opiop65
Published on 2012-10-03T00:23:33Z Indexed on 2012/10/03 9:51 UTC
Read the original article Hit count: 238

Filed under:
|
|

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)

© Game Development or respective owner

Related posts about 2d

Related posts about java