C#C
C#3y ago
bialasik__

❔ I am trying to make a simple game in C# console.

Problem: Whenever the player character goes out of bounds/ touches the border, I get an exception. I want the player to bounce back/ stop at the border. I was thinking of resetting velocity, but this doesnt seem to work.

    static void Main(string[] args)
    {
        Game game = new Game();

        Vec playerPosition = new Vec(Console.WindowWidth / 2, Console.WindowHeight / 2);
        Vec playerVelocity = new Vec(0, 0);
        char playerSymbol = 'O';
        GameObject player = new GameObject(playerPosition, playerVelocity, playerSymbol);
        game.AddGameObject(player);

        float deltaTime = 0.2f;
        while (true)
        {
            game.Update(deltaTime);
            game.Draw();

            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    player.velocity.x = -1;
                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    player.velocity.x = 1;
                }
                else if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    player.velocity.y = -1;
                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    player.velocity.y = 1;
                }
            }
            Thread.Sleep(16);
        }
Was this page helpful?