两个轴的 2D 平台碰撞问题 [英] 2D Platformer Collision Problems With Both Axes

查看:27
本文介绍了两个轴的 2D 平台碰撞问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C++ 和 SDL 开发一款小型 2D 平台游戏/格斗游戏,但在碰撞检测方面遇到了一些麻烦.

I'm working on a little 2D platformer/fighting game with C++ and SDL, and I'm having quite a bit of trouble with the collision detection.

关卡由一组图块组成,我使用 for 循环遍历每个图块(我知道这可能不是最好的方法,我也可能需要帮助).对于角色的每一侧,我将其向该方向移动一个像素并检查是否发生碰撞(我还检查角色是否正在向该方向移动).如果发生碰撞,我将速度设置为 0 并将玩家移动到图块的边缘.

The levels are made up of an array of tiles, and I use a for loop to go through each one (I know it may not be the best way to do it, and I may need help with that too). For each side of the character, I move it one pixel in that direction and check for a collision (I also check to see if the character is moving in that direction). If there is a collision, I set the velocity to 0 and move the player to the edge of the tile.

我的问题是,如果我首先检查水平碰撞,并且玩家以每帧超过一个像素的速度垂直移动,它会处理水平碰撞并将角色移动到图块的一侧,即使图块在下方(或以上)字符.如果我先处理垂直碰撞,它会做同样的事情,除了它是针对水平轴做的.

My problem is that if I check for horizontal collisions first, and the player moves vertically at more than one pixel per frame, it handles the horizontal collision and moves the character to the side of the tile even if the tile is below (or above) the character. If I handle vertical collision first, it does the same, except it does it for the horizontal axis.

如何在没有这些问题的情况下处理两个轴上的碰撞?有没有比我的处理方式更好的方法来处理碰撞?

How can I handle collisions on both axes without having those problems? Is there any better way to handle collision than how I'm doing it?

推荐答案

XNA 的 2D平台游戏示例 也使用基于图块的碰撞.他们在那里处理它的方式非常简单,可能对您有用.这是对其中内容的精简解释(删除特定于他们的演示内容):

XNA's 2D platformer example uses tile-based collision as well. The way they handle it there is pretty simple and may useful for you. Here's a stripped down explanation of what's in there (removing the specific-to-their-demo stuff):

  1. 应用移动后,它会检查碰撞.
  2. 它根据玩家的边界框确定玩家重叠的图块.
  3. 它遍历所有这些图块......
  1. After applying movement, it checks for collisions.
  2. It determines the tiles the player overlaps based on the player's bounding box.
  3. It iterates through all of those tiles...
  1. 如果被检查的磁贴无法通过:
  2. 它决定了玩家在 X 轴和 Y 轴上与不可通过瓷砖重叠的距离
  3. 冲突解决仅在浅轴上:
  1. 如果 Y 是浅轴 (abs(overlap.y)
  2. 边界框根据位置变化更新

  • 移动到下一个图块...
  • 它位于 player.cs 的 HandleCollisions() 函数中,如果您获取代码并想查看它们在那里具体做什么.

    It's in player.cs in the HandleCollisions() function if you grab the code and want to see what they specifically do there.

    这篇关于两个轴的 2D 平台碰撞问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆