我正在正方形的所有侧面制作一个四人乒乓球,但在如何增加每个单独的桨叶之间的碰撞方面却一无所获,以免它们在拐角处彼此相撞
import pygame
pygame.init()
### Colors
WHITE = (255, 255, 255)
BLACK = (0,0,0)
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("GNOP")
x = 485
y = 75
x2 = 5
y2 = 75
x3 = 250
y3 = 5
y4 = 485
x4 = 250
width = 10
height = 90
vel = 5
run = True
while run:
print(x4,y4)
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
key= pygame.key.get_pressed()
if key [pygame.K_UP] and y>0:
y -= vel
if key [pygame.K_DOWN]and y<420:
y += vel
if key [pygame.K_w] and y2>0:
y2 -= vel
if key [pygame.K_s]and y2<420:
y2 += vel
if key [pygame.K_c] and x3>0:
x3 -= vel
if key [pygame.K_v] and x3<420:
print(1)
x3 += vel
if key [pygame.K_n] and x4>0:
x4 -= vel
if key [pygame.K_m] and x4<420:
x4 += vel
def ball (self):
# Create the image of the ball
self.image = pygame.Surface([10, 10])
# Color the ball
self.image.fill(BLACK)
# Get a rectangle object that shows where our image is
self.rect = self.image.get_rect()
# Get attributes for the height/width of the screen
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()
# Speed in pixels per cycle
self.speed = 0
# Floating point representation of where the ball is
self.x = 0
self.y = 0
# Direction of ball in degrees
self.direction = 0
# Height and width of the ball
self.width = 10
self.height = 10
# Set the initial ball speed and position
self.reset()
win.fill((230,230,230))
pygame.draw.rect(win,(0, 0, 0), (x, y, width, height))
pygame.draw.rect(win,(255,50,0), (x2, y2, width, height))
pygame.draw.rect(win,(150,15,200), (x3, y3, height, width))
pygame.draw.rect(win,(0,100,255), (x4, y4, height, width))
pygame.display.update()
pygame.quit()
ball()
我需要球拍互相检测并碰撞,而不是彼此相撞,但是我已经看过几个代码,但是我还没有学习如何针对每个单独地做到这一点,这很关键,因为我无法拿到球没有它就可以工作
答案 0 :(得分:0)
如果要检测碰撞:
def touched(tar_x,tar_y,tarimage,tar_x1,tar_y1,tarimage2):
for i in range(tar_x1,tar_x1 + tarimage2.get_width()):
for j in range(tar_y1,tar_y1 + tarimage2.get_height()):
if tar_x < i < tar_x + tarimage.get_width() and tar_y < j < tar_y + tarimage.get_height():
return True
return False
tar_x,tar_y是第一个对象的位置 tar_x1,tar_y1是第二个对象的位置 tarimage,tarimage2是加载到pygame中的图像