pygame碰撞检测导致我的计算机挂起 [英] pygame collision detection causes my computer to hang

查看:38
本文介绍了pygame碰撞检测导致我的计算机挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作类似于agar.io的游戏.我有一个由播放器控制的Blob.它可以四处走动并吃东西.食物也有不同的类别.食物类别的200个实例被创建:

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())

现在一切正常,但是,如果我尝试在所有食物和Blob之间运行碰撞检测,则我的整个计算机都将挂起.这是代码:

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")

我感觉它崩溃了,因为 circle_collision 中的计算非常繁琐,并且我将其计算为一帧200次.这是 circle_collision 函数

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

现在我的问题是如何改善这个circle_collision函数?另外,有没有一种方法可以检查是否只有距离团块一定距离的食物有无碰撞,因此它不必检查所有200种食物.谢谢

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

推荐答案

问题是多次调用

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)

这篇关于pygame碰撞检测导致我的计算机挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆