简体   繁体   English

坠落和xna碰撞

[英]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. 我使用Rectangle类以及平台将主角做成一个矩形。 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. 基本上,除非角色降落在平台上,否则假设角色会一直坠落,那么其y方向/速度应更改为平台的y方向/速度。

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# 我是xna的新手,但我知道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;
            }

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. 您每次都遍历所有平台,因此当一个相交时,重力将为0,但您猜怎么着,它将检查下一个,重力将再次为5。

You'd have to restructure your loop or you could check out this 2D physics engine to handle most of this stuff for you: 您必须重组循环,否则您可以签出此2D物理引擎来为您处理大部分此类工作:

http://farseerphysics.codeplex.com/ http://farseerphysics.codeplex.com/

Microsoft有一个Platformer示例 ,该示例具有丰富的经验和教训。这是一个值得学习的好示例,您不需要任何第三方物理引擎即可为您完成此工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM