pygame collision detection causes my computer to hang

瘦欲@ 提交于 2021-01-28 02:53:24

问题


I am trying to make a game similar to agar.io. I have a blob which is controlled by the player. It can move around and eat food. There is a different class for food as well. 200 instances of the food class is created:

def spawn_food(self):
    if len(self.foods) <= 200:
        self.foods.append(Food())

Everything upuntil now is working fine, however, my entire computer hangs if i try to run the collision detection between all the foods and the blob. This is the code:

  def ate(self):
    for food in self.foods:
        if circle_collision(blob, food):
            d.win.set_caption("eating")
        else:
            d.win.set_caption("not eating")

I have a feeling that it's crashing beacuse the calculation in circle_collision is very computationaly heavy and i am ruunning it 200 times a frame. Here is the circle_collision function

def circle_collision(one, two):
    dx = one.pos[0] - two.pos[0]
    dy = one.pos[1] - two.pos[1]

    distance = math.hypot((dx**2), (dy**2))

    if distance <= (one.radius + two.radius):
        return True
    return False

Now my question is how could i improve this circle_collision function? Also, is there a way to check for collisions only for food withn a certain distance from the blob, so it wouldn't have to check for all 200 of the food. Thanks


回答1:


The issue are the multiple calls to set_caption. The change of the window caption is very expensive and you do it 200 times per frame.
State the current caption in a variable in global scope. Only update the caption when it changes. Furthermore you can break the loop if a collision is detected:

current_caption = ""

def ate(self):
    global current_caption

    new_caption = "not eating"
    for food in self.foods:
        if circle_collision(blob, food):
            new_caption = "eating"
            break

    if new_caption != current_caption:
        current_caption = new_caption 
        d.win.set_caption(current_caption)


来源:https://stackoverflow.com/questions/60323509/pygame-collision-detection-causes-my-computer-to-hang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!