【问题标题】:Problems with list of objects in python [duplicate]python中对象列表的问题[重复]
【发布时间】:2020-01-18 09:10:06
【问题描述】:

嗨,我是游戏开发新手,我正在使用 pygame,现在我遇到了这个问题,我有多个玩家必须同时躲避和杀死的敌人,但我的碰撞检测功能会检查一个敌人的碰撞一次。 除了列表中的第一个敌人外,该功能不适用于列表中的其他敌人。 这是创建敌人和碰撞检测的代码

class Enemy(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width, self.height = 30, 30
        self.vel = 10
        self.color = (0, 0, 255)
        self.rect = (x, y, self.width, self.height)

def create_enemies(n):
    enemies = []
    for i in range(n):
        xcor = randint(0, (W - 50))
        ycor = randint(0, H - H/2)
        enemies.append(Enemy(xcor, ycor))
    return enemies

n = 2

enemies = create_enemies(n)

def collision_detection(obj1, obj2list):
    for obj2 in obj2list:
        if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
            return False
        if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
            return False
        if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
            return False
        if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
            return False
        if obj1.x == obj2.x and obj1.y <= obj2.y + obj2.height:
            return False
        if obj1.x == obj2.x and obj1.y + obj1.height >= obj2.y:
            return False
        else:
            return True

【问题讨论】:

  • 代码格式的反引号是`,而不是单引号'
  • PyGamepygame.Rect(),它具有检查冲突的方法,您不必编写它 - player.rect.colliderect(enemy.rect)。它还有Group,可用于检查碰撞将列出的敌人。

标签: python


【解决方案1】:

您的问题在于您的碰撞检测逻辑。你的逻辑如下:

主循环> 调用collision_detection > 遍历对象

应该是:

主循环> 遍历对象> 调用collision_detection

这是因为如果obj2list 中的第一个对象与obj1 发生冲突,它会从函数中返回并且不会检查其余对象。

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2012-04-05
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多