我如何在正方形和圆形之间进行碰撞以触发pygame中的游戏?

问题描述 投票:1回答:2

我制作的游戏中有一堆掉落的圆圈,玩家(正方形)需要避免掉落。问题是我找不到使圆圈与玩家碰撞以触发游戏的方法。有什么方法可以使正方形和圆形发生碰撞以触发游戏结束,或者使游戏在pygame中退出?

import pygame
from pygame.locals import *
import os
import random
import math
import sys
import time

white = (255,255,255)
blue = (0,0,255)
gravity = 10
size =10
height = 500
width =600
varHeigth = height
ballNum = 5
eBall = []
apGame = pygame.display.set_mode((width, height))
pygame.display.set_caption("AP Project")

clock = pygame.time.Clock()

class Player(object):

  def __init__(self):
    red = (255, 0, 0)
    move_x = 300
    move_y = 400
    self.rect = pygame.draw.rect(apGame,red, (move_x, move_y, 10, 10))
    self.dist = 10

  def handle_keys(self):
    for e in pygame.event.get():
      if e.type == pygame.QUIT:
        pygame.quit();
        exit()
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
      self.draw_rect(-1, 0)
    elif key[pygame.K_RIGHT]:
      self.draw_rect(1, 0)
    elif key[pygame.K_ESCAPE]:
      pygame.quit();
      exit()
    else:
      self.draw_rect(0, 0)

  def draw_rect(self, x, y):
    red = (255, 0, 0)
    black = (0, 0, 0)
    '''apGame.fill(black)'''
    self.rect = self.rect.move(x * self.dist, y * self.dist);
    pygame.draw.rect(apGame, red , self.rect)
    pygame.display.update()


  def draw(self,surface):
    red = (255, 0, 0)
    move_x = 300
    move_y = 400
    pygame.draw.rect(apGame, red, (move_x, move_y, 10, 10))


move_x = 300
move_y = 400
red = (255, 0, 0)
black = (0, 0, 0)
player = Player()
clock = pygame.time.Clock()
'''apGame.fill(black)'''
player.draw(apGame)
pygame.display.update()

for q in range(ballNum):
  x = random.randrange(0, width)
  y = random.randrange(0, varHeigth)
  eBall.append([x, y])

while True:

  apGame.fill(black)


  for i in range(len(eBall)):

    pygame.draw.circle(apGame, blue, eBall[i], size)

    eBall[i][1] += 5

    if eBall[i][1] > height:

        y = random.randrange(-50, -10)
        eBall[i][1] = y

        x = random.randrange(0, width)
        eBall[i][0] = x

  player.handle_keys()
  pygame.display.flip()
  clock.tick(30)
python pygame collision-detection
2个回答
0
投票

使用球的边界矩形进行碰撞测试就足够了。绑定的pygame.Rectpygame.Rect返回。如果2个矩形相交,则可以通过pygame.draw.circle()进行评估。

例如:

pygame.draw.circle()

如果要在单独的循环中进行碰撞测试,则必须手动构造球的边界矩形:

colliderect()

0
投票

[pygame rect有碰撞检查,可以检测rect之间或rect与点之间的碰撞。还有一些精灵的碰撞例程,这些例程将执行基于圆的碰撞检查(请参见colliderect())。但是我不相信有任何内置的例程可以绕圈来纠正碰撞检查。

正如@ rabbid76在他的回答中所说,通常人们只是使用rect作为圆来近似它。

如果缩小矩形,则用于碰撞检测的矩形要比圆的矩形边界框小一点,这样拐角的出角就少了(但实际上在矩形的顶部,底部,左侧和右侧稍微偏内)圆圈),实际上您并未真正使用该圆圈通常并不明显。不过,这并不完美。

您还可以使用遮罩并对其进行while True: # [...] for i in range(len(eBall)): ball_rect = pygame.draw.circle(apGame, blue, eBall[i], size) if player.rect.colliderect(ball_rect): print("hit") # [...] 碰撞检查。 IT在计算上更加昂贵。因此,如果您采用这种方式,则需要牢记这一点。

如果您确实需要,可以自行编写。

© www.soinside.com 2019 - 2024. All rights reserved.