我已经为三个沙滩球在屏幕上弹跳编写了一个动画(用Python)。我现在希望它们全部碰撞并能够相互弹开。我非常感谢您能提供的任何帮助。
import pygame
import random
import sys
class Ball:
def __init__(self,X,Y):
self.velocity = [1,1]
self.ball_image = pygame.image.load ('Beachball.jpg'). convert()
self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
self.sound = pygame.mixer.Sound ('Thump.wav')
self.rect = self.ball_image.get_rect (center=(X,Y))
if __name__ =='__main__':
width = 800
height = 600
background_colour = 0,0,0
pygame.init()
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball animation")
num_balls = 3
ball_list = []
for number in range(num_balls):
ball_list.append( Ball(random.randint(10, (width - 10)),random.randint(10, (height - 10))) )
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
sys.exit(0)
window.fill (background_colour)
for ball in ball_list:
if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
ball.sound.play()
ball.velocity[0] = -1 * ball.velocity[0]
if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
ball.sound.play()
ball.velocity[1] = -1 * ball.velocity[1]
ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
window.blit (ball.ball_image, ball.ball_boundary)
pygame.display.flip()
任意形状的碰撞检测通常非常棘手,因为您必须弄清楚是否有任何像素发生碰撞。
使用圆圈实际上更容易。如果有两个半径为 r1 和 r2 的圆,如果圆心之间的距离小于 r1+r2,则发生碰撞。
两个中心 (x1,y1) 和 (x2,y2) 之间的距离可以计算并比较为:
d = sqrt((y2-y1) * (y2-y1) + (x2-x1) * (x2-x1));
if (d < r1 + r2) { ... bang ... }
或者,正如 jfclavette 指出的那样,平方根的成本很高,因此最好仅使用简单的运算进行计算:
dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1);
if (dsqrd < (r1+r2)*(r1+r2)) { ... bang ... }
棘手的一点在于计算新的运动向量(给定对象(x,y)随时间变化的速率),因为您需要考虑当前的运动向量和接触点。
我认为作为第一次剪切,您应该先反转运动向量来测试碰撞检测是否有效。
然后问另一个问题 - 最好将各个问题具体化,以便得到有针对性的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)