Search code examples
c#xnacollisiongravity

falling and collisions on xna


im making a platform type of game. I made my main character a rectangle using the Rectangle class, as well as the platforms. The platforms are constantly moving upward on the screen, and when my character collides with the top of the platform, I want him to land and move at the same speed as the platform, otherwise, he should be falling. I got everything to work except the falling part. If i turn on the falling, it never stays on the platforms, but if I turn on falling, it works fine. Basically the character is suppose to be falling the whole time unless it lands on a platform, then its y direction/speed should change to that of the platforms.

here is that part of the code, any help on how to make the character fall whenever not colliding with the platforms would be great. I know what I am doing may not be the most effiecent way to do this, if there is a better way I would love to know. I'm new to xna, but I know java/c#

            Rectangle playerRec = new Rectangle((int)player.position.X, (int)player.position.Y,player.width, player.height);
        foreach (Platforms platform in platforms)
        {
            Rectangle platformRec = new Rectangle((int)platform.position.X, (int)platform.position.Y, platform.width, platform.height);
            if ((playerRec.Intersects(platformRec) && (playerRec.Y + playerRec.Height) - platformSpeed < platformRec.Y) &&
                (playerRec.X < platformRec.X + platformRec.Width && playerRec.X + playerRec.Width > platformRec.X))
            {
                gravity = 0;
                player.position.Y -= platformSpeed;

            }
            else if(player.position.Y != platform.position.Y)
            {
                gravity = 5;
                //player.position.Y += gravity;
            }

Solution

  • Your problem is most likely that you aren't BREAKING OUT of the loop when you hit an intersection. You're looping through ALL the platforms every time so when one intersects, gravity will = 0 but then guess what, it'll check the next one and gravity will be 5 again.

    You'd have to restructure your loop or you could check out this 2D physics engine to handle most of this stuff for you:

    http://farseerphysics.codeplex.com/