2D 平台游戏的碰撞检测

我正在开发平台游戏,我想与平台进行基本的碰撞,遗憾的是仍然无法正确完成。玩家移动的计算公式如下:

velocity += acceleration
position += velocity + 0.5 * acceleration

所有变量都是具有和值的向量。这按预期工作,问题是碰撞。我的规则是:xy

  • 降落在平台上时停止摔倒。

  • 从平台上运行时开始下降。

  • 在跳跃过程中撞到平台时停止向上移动。

  • 撞墙时停止向一侧移动,但能够向相反的方向移动。

检查底部是否与平台碰撞非常简单,但棘手的部分是检测,哪一侧与平台碰撞,并能够为玩家设置适当的位置。

我试图从每一侧检测角落和中间,但由于我的速度不是每帧1px,有时玩家会下降到快速,并且也被检测到侧面。

检测哪一侧碰撞的好方法是什么?


白衣染霜花
浏览 188回答 2
2回答

三国纷争

我在javascript中有几个类似平台游戏的游戏,这就是我实现碰撞的方式:1.降落在平台上时停止掉落:你可以给你的精灵一个矩形作为边界区域,然后使用Pygames内置的Rect类来检测交叉点。当您的精灵命中框(矩形)和平台矩形(另一个矩形)之间发生这种交集时,您可以将玩家的Y速度设置为0。2. 在平台外运行时开始下降。我通常有一个专门用于重力的变量,并且简单地不断将其应用于精灵以将其向下推。这样,在您不再与平台相交后,它将向下下降。3.在跳跃过程中撞到平台时停止向上移动:与交叉点前相同,只需在矩形碰撞后将Y速度设置为0,并让玩家由于恒定的重力而摔倒。4.撞墙时停止向侧面移动,但能够向相反的方向移动:同样的事情,但这次将X速度设置为0。(如果你被困在墙上,你总是可以将X设置为大于0,以推动你回到游戏中)还有一点需要注意,如果您只想在子画面击中平台的某个边缘时执行某些操作,则可以创建一个与子画面侧面对齐的矩形。例如,如果我想查看某些内容是否与我的精灵的左侧相交,我可以使用 - 高度:相同高度 - 宽度:1 - x:x + 宽度 - y:相同y有关矩形的文档:https://www.pygame.org/docs/ref/rect.html

慕娘9325324

好吧,这里有代码可以帮助检测你什么时候可以从平台跳转:self.rect.y += 2platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)self.rect.y -= 2# If it is ok to jump, set our speed upwardsif len(platform_hit_list) > 0:&nbsp; &nbsp; velocity += acceleration&nbsp; &nbsp; position += velocity + 0.5 * acceleration然后编写代码,用于检测何时落入平台:if self.rect.y >= constants.SCREEN_HEIGHT and self.change_y >= 0:&nbsp; &nbsp; self.change_y = 0&nbsp; &nbsp; self.rect.y = constants.SCREEN_HEIGHT最后是冲突代码:block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)for block in block_hit_list:&nbsp; &nbsp; # If we are moving right,&nbsp; &nbsp; # set our right side to the left side of the item we hit&nbsp; &nbsp; if self.change_x > 0:&nbsp; &nbsp; &nbsp; &nbsp; self.rect.right = block.rect.left&nbsp; &nbsp; elif self.change_x < 0:&nbsp; &nbsp; &nbsp; &nbsp; # Otherwise if we are moving left, do the opposite.&nbsp; &nbsp; &nbsp; &nbsp; self.rect.left = block.rect.right# Move up/downvelocity += accelerationposition += velocity + 0.5 * acceleration# Check and see if we hit anythingblock_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)for block in block_hit_list:&nbsp; &nbsp; # Reset our position based on the top/bottom of the object.&nbsp; &nbsp; if self.change_y > 0:&nbsp; &nbsp; &nbsp; &nbsp; self.rect.bottom = block.rect.top&nbsp; &nbsp; elif self.change_y < 0:&nbsp; &nbsp; &nbsp; &nbsp; self.rect.top = block.rect.bottom&nbsp; &nbsp; # Stop our vertical movement&nbsp; &nbsp; self.change_y = 0希望这一切都能以某种方式帮助您为您提供所需的答案。请注意,这些块指的是平台,并将检查给定列表中的每个平台,我使用rects,因为它是检查碰撞的最佳方法之一。至于change_x和change_y它只是存储玩家移动多少的变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python