如何解决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 举报,一经查实,本站将立刻删除。