Search code examples
c#xnacollision-detection

My player collision is not working correctly


The colision is working but its something wrong with theese lines since the player is just standing still at the start position x10 y10

for (int i = 0; i < sprites.Length; i++)
            {
                if (player.Top > sprites[i].Top && player.Bottom < sprites[i].Top) //Checking for intersection at the top of the player
                {
                    player_Collision1 = true; //Found collision
                }

                else if (player.Bottom > sprites[i].Top && player.Bottom < sprites[i].Bottom) //Checking for intersection at the bottom of the player
                {
                    player_Collision2 = true; //Found collision
                }

                else if (player.Left > sprites[i].Right && player.Left < sprites[i].Left) //Checking for intersection at the left of the player
                {
                    player_Collision3 = true; //Found collision
                }

                else if (player.Right > sprites[i].Left && player.Right < sprites[i].Right)//Checking for intersection at the right of the player
                {
                    player_Collision4 = true; //Found collision
                }
            }

Im using the XNA's rectangle and player is name of one rectangle and sprites is an array of all the rectangles that player can collide with, The XNA rectangle lets you get the cordinates of the sides of the rectangle as you se me do: player.Top player.Bottom etc etc.


Solution

  • The logic is really messed up. The first if will never be true as the player.top cant be below the sprite.top AND the player.bottom above the sprite.top. What I think you meant was if (player.Top > sprites[i].Top && player.Bottom < sprites[i].Bottom) Even still, it will evaluate to true when they don't collide. Look at this picture as to why. You also need to check the X axis to determine a proper collision.

    The other ifs have the same issue as the first. Both in comparing bottom/top and top/bottom and returning true when there is no collision. That being said, I you are trying to do a poor-man "line of sight" scenario where you just want to see if the player is standing in a location that the sprite could "see", I am wrong.

    I suggest taking a look at the platformer starter kit provided on the App Hub site as well as some documention on it. Specifically, look at the collision detection (in Player.cs CheckCollision()...or HandleCollision() I foget the exact name. It should be obvious.) You will be able to see how they determine which direction the player is colliding. They use it to see if a player can jump through a platform, but not fall through it.