Search code examples
2dcollision-detection

Platformer collision?


I've been trying to figure out now if i have a map in my platformer game and i want my character be able to jump on some platform for example.. Is there any easy way to tell the game where the platforms are and where the player can jump and start??

Also the games like Super Mario Bros and such are their maps made in .txt files ? Because i watched a tutorial for maps and he said all proffesional game developers make a .txt file for the map and write numbers for example:

111111111111111111111

111111111111111111111

111111111111111111111

111111111111111111111

222222222222222222222

To create a map.. Is this correct or how did the developers do maps in the Super mario bros or Mega man games ??

What i am wondering is.. If i want my player to be able to jump up on some platform or something.. Thats what am looking for.


Solution

  • A very simple example:

    You can represent the map by a matrix of e.g. numbers. A number of one will represent an obstacle and a number of zero will represent open space.

                       [000000]              [      ]
    int[] map    ==    [000000]      ==      [      ]
                       [000111]              [   xxx]
                       [001111]              [  xxxx]
    

    The player object must also have a coordinate inside the matrix, where horizontal position (X) is the column and vertical position (Y) is the row, and a velocity (direction and speed). The velocity is controlled by user input, like for example pressing the right arrow will set the X-direction to speed +1.

    int xPos;
    int yPos
    
    int xSpeed;
    int ySpeed;
    
    while(true) {
        // Check user input
        if (upArrow()) {
            ySpeed = 1;
        }
        if (downArrow()) {
            ySpeed = -1;
        }
        if (leftArrow()) {
            ySpeed = -1;
        }
        if (rightArrow()) {
            ySpeed = 1;
        }
    
        // Update player position
        xPos = xPos + xSpeed;
        yPos = yPos + ySpeed;
    
    // ...
    

    Now you just have to check the number in the matrix for the current position the player object has in the matrix. If it's a zero do nothing, if it's a 1: set the speed to 0.

        int mapObstacle = map[xPos, yPos];
        if (mapObstacle == 1) {
            // Stop player movement
            xSpeed = 0;
            ySpeed = 0;
        }
    }
    

    To keep the map in txt file you must get your game to read/write the map matrix from the file. Below is an example for reading.

    int n = 0;
    while (mapFile.hasNextLine()) {
        String mapLine = mapFile.nextLine();
    
        for (int i = 0, n = mapLine.length; i < n; i++) {
            int mapObstacle = Integer.parseInt(mapLine.charAt(i));
            map[n, i] = mapObstacle; // Read map layout
        }
        n++;
    }