Search code examples
c#console-applicationcollision-detection

C# Console Collision


Currently I am making a console game (a rougelike) and I needed some advice on the collision events. I need to tell if there is a wall (▒) next to the player (@) and if so disallow the player from moving in that direction. Does anyone have any ideas about how I could do this with the console in C#?

If needed I can provide some of my code.


Solution

  • There are multiple ways to handle this. I would expect you have a two-dimensional array representing the game map. One simple method is to add a method CheckMove which validates an attempted move. If not valid, then the move is not performed. Here's a sort of pseudo-code example.

    public bool CheckMove(int newY, int newX) {
        if (grid[newY][newX] == WALL)
            return false;
        if (newY < 0 || newY > Y_MAX || newX < 0 || newX > X_MAX)
            return false;
        return true;
    }
    
    public void Move(int dir) {
        // calc new x & y
    
        if (!CheckMove(newY, newX)) return;
    
        // else do the move
    }