Pygame中许多相同类别元素的碰撞检测

问题描述

**我正在做弹跳球的项目。球(同等级的元素)应该与墙壁互相弹跳。可以有很多球(并且球的数量是可变的),我必须创建通用方法,该方法可以检查同一时刻每个球之间的碰撞。 **

我的主要问题是,球之间的弹跳是随机发生的,大多数情况下它们只是不起作用。据我从this source所读到的情况可能会发生,因为球的移动速度快于每帧2 *半径。知道怎么适应吗?

class Ball:
"""
Class to keep track of a ball's location and vector.
"""
def __init__(self):
    self.x = 0
    self.y = 0
    self.change_x = 0
    self.change_y = 0


def make_ball():
"""
Function to make a new,random ball.
"""
   ball = Ball()
   # Starting position of the ball.
   # Take into account the ball size so we don't spawn on the edge.
   ball.x = random.randrange(300 + BALL_SIZE,300 + nL - BALL_SIZE) 
   ball.y = random.randrange(25 + BALL_SIZE,25 + nH - BALL_SIZE)

   # Speed and direction 
   ball.change_x = random.randrange(-2,2)
   ball.change_y = random.randrange(-2,2)

   return ball


def checkCollisionBall(first,second):
    """
    Function to check if collision happened
    """
    xdistance = first.x - second.x
    ydistance = first.y - second.y
    distance = math.sqrt((pow(xdistance,2) + pow(ydistance,2)))        
    if(2 * maxdistance < distance and distance < 2* maxdistance + 0.1):
        return True



def CollisionWithOtherBall(first,second):
"""
Quick swap to check if collision detection is working
"""
   oldVeLocity1 = first.change_x
   oldVeLocity2 = second.change_x 
   first.change_x = oldVeLocity2
   second.change_x = oldVeLocity1    

"""
This is how I am looking for collisions.
"""
for i in range(0,len(ball_list)):
            for j in range(i+1,len(ball_list)):
                if(checkCollisionBall(ball_list[i],ball_list[j]) == True):
                    print('BOOOOOM')
                    CollisionWithOtherBall(ball_list[i],ball_list[j])

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)