Collision Code Help

Category: c# language

Question

MissAshleyFox on Thu, 13 Dec 2012 18:32:38


Hey Everyone,

Okay so im making an 8 bit game (similar style to Zelda for NES) and I need code that stops my player (picturebox called "PbPlayer") from running through the enemy (picturebox called "enemy")

My code that moves the player using WASD:

public partial class Form1 : Form { int moveUp = 0; int moveDown = 0; int moveLeft = 0; int moveRight = 0; int speed = 5; private void Form1_KeyDown(object sender, KeyEventArgs e) { // Move up if (e.KeyCode == Keys.W) { moveUp = 1; moveDown = 0; moveLeft = 0; moveRight = 0; } // Move down if (e.KeyCode == Keys.S) { moveDown = 1; moveUp = 0; moveLeft = 0; moveRight = 0; } // Move left if (e.KeyCode == Keys.A) { moveLeft = 1; moveRight = 0; moveUp = 0; moveDown = 0; } // Move right if (e.KeyCode == Keys.D) { moveRight = 1; moveLeft = 0; moveUp = 0; moveDown = 0; } private void tMove_Tick(object sender, EventArgs e) { // Up if (moveUp == 1) { pbPlayer.Top -= (speed); } // Down if (moveDown == 1) { pbPlayer.Top += (speed); } // Left if (moveLeft == 1) { pbPlayer.Left -= (speed); } // Right if (moveRight == 1) { pbPlayer.Left += (speed); } } }

Also, the enemy is programmed to walk towards the player when the player comes within a certain range. This is the code:

 private void tEnemies_Tick(object sender, EventArgs e)
        {
           // Makes the enemy walk towards the player when the enemy approaches it
                if (pbPlayer.Bounds.Left < enemy.Left)
                {
                    if (pbPlayer.Bounds.Left > enemy.Left - 200)
                    {
                        enemy.Left -= 1;
                    }
                }
                if (pbPlayer.Bounds.Bottom < enemy.Bottom)
                {
                    if (pbPlayer.Bounds.Bottom > enemy.Bottom - 200)
                    {
                        enemy.Top -= 1;
                    }
                }
                if (pbPlayer.Bounds.Right > enemy.Left)
                {
                    if (pbPlayer.Bounds.Right < enemy.Left + 200)
                    {
                        enemy.Left += 1;
                    }
                }
                if (pbPlayer.Bounds.Bottom > enemy.Bottom)
                {
                    if (pbPlayer.Bounds.Bottom < enemy.Bottom + 200)
                    {
                        enemy.Top += 1;
                    }
                }

With this code in mind, can anyone think of a way to keep them from being able to go through each other. Keep in mind that you will have to stop the player AND the enemy from running into one another, because they both have ways of moving.

Thanks for the help :)

-LimeFox

Replies

Brad Semrad on Thu, 13 Dec 2012 20:59:54


I think you also need to take into account the width and/or height of the player and enemies.

Thanks,

Brad