Pygame – CollideRect – 但他们如何碰撞?

我遇到了一些麻烦,弄清楚如何处理在顶部底部碰撞的碰撞。 如何指定这些碰撞?

这是一个小小的代码片段,让您了解我的方法。 现在它在哪里碰撞并不重要。

# the ball has hit one of the paddles. send it back in another direction. if paddleRect.colliderect(ballRect) or paddle2Rect.colliderect(ballRect): ballHitPaddle.play() if directionOfBall == 'upleft': directionOfBall = 'upright' elif directionOfBall == 'upright': directionOfBall = 'upleft' elif directionOfBall == 'downleft': directionOfBall = 'downright' elif directionOfBall == 'downright': directionOfBall = 'downleft' 

提前致谢。

 **EDIT** Paddle rect: top ____ | | | | | | Sides | | ---- bottom 

我需要知道,如果球击中顶部或底部。

角度的构成:

基本上你必须看看你用于划桨的矩形的中心与球的矩形的中心之间的角度(也可以是一个点,因为我们把球的矩形折成一个点)。

在这里输入图像说明

然后将中心点之间的角度与桨叶角点给出的象限进行比较(这给出了左,右,上,下)。 下面的程序只是通过一些规范化来简化数组的查找。

testing程序

与您的问题相关的部分实际上是DirRect类。

 import pygame import math class DirRect(pygame.Rect): def direction_to_rect(self, drect): ar = math.atan2(self.centery - self.top, self.right - self.centerx) # half of the angle of the right side # construct the corner angles into an array to search for index such that the index indicates direction # this is normalized into [0, 2π] to make searches easier (no negative numbers and stuff) dirint = [ 2*ar, math.pi, math.pi+2*ar, 2*math.pi] # calculate angle towars the center of the other rectangle, + ar for normalization into ad = math.atan2(self.centery - drect.centery, drect.centerx - self.centerx) + ar # again normalization, sincen atan2 ouputs values in the range of [-π,π] if ad < 0: ad = 2*math.pi + ad # search for the quadrant we are in and return it for i in xrange(len(dirint)): if ad < dirint[i]: return i # just in case -1 as error indicator return -1 pygame.init() screen = pygame.display.set_mode([400,400]) screen.fill([255,255,255]) # This is the paddle paddle = DirRect( (150,150),(40,20) ) # colorize directional information colors = [ (255,0,0), #right (0,255,0), #up (0,0,255), #left (0,0,0), #down (255,255,255) # error = -1 ] #show direction for every point dsurf = pygame.display.get_surface() for x in xrange(dsurf.get_width()): for y in xrange(dsurf.get_height()): prect = pygame.Rect((x,y),(0,0)) dsurf.set_at( (x,y), colors[paddle.direction_to_rect(prect)]) #show paddle pygame.draw.rect( dsurf, (128,128,128), paddle, 1) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False pygame.display.update() pygame.quit() 
 def on_collide(paddle, ball): # we collided, so which side? Args are the `Rect`s of paddle and ball. if paddle.centery < ball.centery: print("paddle bottom") elif paddle.centery > ball.centery: print("paddle top") if paddle.centerx < ball.centerx: print("paddle right") elif paddle.centerx > ball.centerx: print("paddle left")