Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在pygame中防止我的a精灵穿过对象?_Python_Python 2.7_Pygame_Collision Detection_Sprite - Fatal编程技术网

Python 如何在pygame中防止我的a精灵穿过对象?

Python 如何在pygame中防止我的a精灵穿过对象?,python,python-2.7,pygame,collision-detection,sprite,Python,Python 2.7,Pygame,Collision Detection,Sprite,所以我一直在做一个游戏,到目前为止最大的问题是我们不能让玩家与球场上的任何物体碰撞。相反,它们直接穿过树。谁能告诉我为什么? 以下是我尝试用于碰撞检测的代码: 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.rec

所以我一直在做一个游戏,到目前为止最大的问题是我们不能让玩家与球场上的任何物体碰撞。相反,它们直接穿过树。谁能告诉我为什么? 以下是我尝试用于碰撞检测的代码:

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

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

几乎是正确的理论。您仅检查
播放器
矩形位置是否与
矩形位置的边界完全相同。这种情况很少发生。您还需要检查玩家是否位于树的边界之间,更像这样:

# 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

你在用pygame吗?如果是,则有内置的
colliderect
功能(文档)

如果没有:

  • 一个相对深入的讨论,考虑到平台游戏的设计
  • 是否只是轴对齐(即未旋转)矩形的裸骨二维碰撞检测
请记住,快速移动的对象可能会使碰撞检测变得非常困难,因为它们在一帧内“越过”对象!有更先进的技术来处理这个问题,但是现在,试着让你的碰撞框相对较大,而事情的发展相对缓慢


编辑:哎呀,我的第一句话听起来很粗鲁。我只是忘记了这篇文章的标题…

谢谢!我们尝试使用collidedetect时遇到的主要问题是,我们无法让玩家做出适当的反应。因为游戏是自上而下的,所以我们无法让玩家在屏幕上正确后退?或者在碰撞后移动?这是一个自上而下的游戏。每当玩家跑进一棵树,它就会直接穿过这棵树。我们可以检测到碰撞,但当我们检测到时,我们无法让玩家从树上“反弹”,最好是有多个碰撞框。这在平台游戏中几乎总是必要的,因为你希望玩家在与墙壁碰撞时停止水平移动,但显然不是在他们的“脚”接触地面时。当你说反弹时,你的意思是他应该反弹吗?这种行为有点棘手,因为你需要建立几帧“反弹”,仅仅测试一帧碰撞是不够的。