【问题标题】:How do I prevent my a sprite from going through an object in pygame?如何防止我的精灵穿过 pygame 中的对象?
【发布时间】:2014-12-10 02:08:23
【问题描述】:

所以我一直在开发一款游戏,目前最大的问题是我们无法让玩家与场上的任何物体发生碰撞。相反,他们直接穿过树。谁能告诉我为什么? 这是我尝试用于碰撞检测的代码:

for tree in treelist:


    if self.player.rect.x == tree.rect.x:
        self.player.rect.x == self.player.rect.x - 2
    if self.player.rect.x == tree.rect.x + tree.rect.width:
        self.player.rect.x == self.player.rect.x + 2

    if self.player.rect.y == tree.rect.y:
        self.player.rect.y == self.player.rect.y - 2
    if self.player.rect.y == tree.rect.y + tree.rect.height:
        self.player.rect.y == self.player.rect.y + 2

这在理论上是正确的,还是我完全错了?

【问题讨论】:

标签: python python-2.7 pygame collision-detection sprite


【解决方案1】:

你在使用 pygame 吗?如果是这样,则有内置的colliderect 函数(文档here)。

如果没有:

  • Here's 一个相对深入的讨论,设计时考虑了平台游戏。
  • This 只是轴对齐(即未旋转)矩形的准系统二维碰撞检测

请记住,快速移动的对象会使碰撞检测变得非常困难,因为它们会在一帧的范围内“越过”对象!有更先进的技术可以解决这个问题,但现在,请尝试让碰撞框相对较大,并且移动速度相对较慢。

编辑:糟糕,我的第一句话听起来很粗鲁。我只是不知怎的忘记了这篇文章的标题是什么......

【讨论】:

  • 谢谢!当我们尝试使用 collidedetect 时遇到的主要问题是我们无法让玩家做出适当的反应。因为游戏是自上而下的,我们永远无法让玩家正确地向后移动
  • 向后移动 = 在屏幕上向下移动?还是在碰撞后移动?
  • 这是一款自上而下的游戏。每当玩家碰到一棵树时,它就会直接穿过树。我们可以检测到碰撞,但是当我们检测到碰撞时,我们无法让玩家从树上“弹回”
  • 最好有多个碰撞盒。这对于平台游戏几乎总是必要的,因为您希望玩家在与墙壁碰撞时停止水平移动,但显然不是当他们的“脚”接触地面时。当你说弹跳时,你真的是说他应该弹跳吗?这种行为有点棘手,因为您需要建立几帧“反弹”,仅测试一帧碰撞是不够的。
【解决方案2】:

几乎是合理的理论。您只是检查player 矩形位置是否与tree 矩形位置的边界完全相同。很少会出现这种情况。您还需要检查玩家是否在树的边界之间,更像这样:

# check if player is overlapping the tree
if tree.rect.x <= self.player.rect.x <= tree.rect.x + tree.rect.width:
    # decide on how to move player away from the tree depending on previous frame
    # if player is moving forward, send them backwards from tree
    if self.player.rect.prev_x < self.player.rect.x:
        self.player.rect.x -= 2
    # otherwise send them forwards from tree
    else:
        self.player.rect.x += 2

重叠检查的确切逻辑以及重叠时的反应完全取决于您,但这种事情应该有效。请注意,您需要跟踪玩家在前一帧中的位置,否则您将不知道他们从哪个方向撞击树。你可以这样做:

self.player.rect.prev_x = self.player.rect.x
self.player.rect.x += player_velocity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多