python - pygame 中的碰撞不起作用(对象发生碰撞但代码未触发)

标签 python python-3.x pygame

我正在为学校项目制作 Pygame 程序。玩家角色将穿过敌方 Sprite 而不触发碰撞。我该如何解决这个问题?

如果两个 Sprite 之间有任何重叠,则应运行 CODE。

if CharY > thing_starty and CharY < thing_starty + Enemy2_height or CharY+PCHeight > thing_starty and CharY + PCHeight < thing_starty + Enemy2_height:
    if CharX > thing_startx and CharX < thing_startx + Enemy2_width or CharX + PCWidth > thing_startx and CharX + PCWidth < thing_startx + Enemy2_width:
        CODE

最佳答案

我建议使用pygame.Rect对象和.colliderect()检查两个矩形的碰撞:

# detects collisions
charRect  = pg.Rect(CharX, CharX, PCWidth, PCHeight)
enemyRect = pg.Rect(thing_startx, thing_starty, Enemy2_width, Enemy2_height)
if charRect.colliderect(enemyRect):
    # [...]
    # CODE
<小时/>

如果您想自己进行碰撞检测,那么您必须检查矩形在两个维度上是否重叠。

范围 [x1, x1+w1] 与范围 [x2, x2+w2] 重叠如果满足以下条件:

intersect = x1 < x2+w2 and x2 < x1+w1

注意,w1w2 必须大于 0。

对两个维度都执行此操作:

if CharX < thing_startx + Enemy2_width  and thing_startx < CharX + PCWidht and \
   CharY < thing_starty + Enemy2_height and thing_starty < CharY + PCHeight
    # [...]
    # CODE

关于python - pygame 中的碰撞不起作用(对象发生碰撞但代码未触发),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836336/

相关文章:

python - 为什么 "get_rect()"不适用于列表?

python - 将两个 pygame.Color 对象混合在一起

python - 如何将pygame中的多个图像添加到网格上?

python - 匹配字符串中的所有标识符

python - conda使用/usr/local/bin/python代替conda环境python

获取 pandas 数据框中元素的序列相关性的 Pythonic 方法

javascript - 有选择地展平嵌套 JSON 结构

python - Tweepy 流媒体过滤器字段

python-3.x - 向左移动时如何修复错误的减速?

python - 显示 : character in the timezone offset using datetime. strftime