如何在没有精灵的乒乓球基本游戏中检测桨和球之间的碰撞

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

对于我的Dofe Gold,我在pygame中创建了一个pong游戏,因为这是我第一次使用pygame,我没有使用精灵,因为这并没有发生在我身上。我现在想要一个解决方案,这将允许我解决我的问题,而无需用精灵重写我的代码。注意:我希望这仍然是我的代码所以我不会接受别人重写的解决方案,因为这将带走任何成就感。提前谢谢了。我的代码:

import pygame
import random
global vel
run = True
def pong():
    global run
    collision = 0
    pygame.init()
    screen = (600, 600)
    window = pygame.display.set_mode((screen))
    pygame.display.set_caption("Pong")
    x = 300
    y = 590
    coords = (300, 150)
    width = 175
    height = 10
    vel = 10 - selection
    velx = 10
    vely = 10
    while run == True:
        pygame.time.delay(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        keys = pygame.key.get_pressed()        

        if keys[pygame.K_LEFT] and x>0:
            x -= vel
        elif keys[pygame.K_RIGHT] and x<600-width:
            x += vel
        if event.type == pygame.MOUSEBUTTONUP:
            pygame.quit()
            quit()
        paddlecoords = (x, y, width, height)
        window.fill((255, 255, 255))
        ball = pygame.draw.circle(window, (255,0,255), coords,(35), (0))
        paddle = pygame.draw.rect(window, (0, 0, 0), paddlecoords)
        pygame.display.update()
        coords=((int(coords[0])+velx), (int(coords[1])+vely))
        if coords[0]>600-35:
            velx = -velx
        elif coords[0]<35:
            velx = -velx
        elif coords[1]<35:
            vely = -vely
        elif coords[1]>600-35:
            vely = -vely

selection =input("Do you want to play\n1)easy\n2)medium\n3)hard\n4)impossible?\n")
if selection.isdigit():
    if 0 < int(selection) < 5:
        selection = int(selection)
        selection = (selection-1)*2
    else:
        print("must be between 1 and 4")
else:
    print("number must be an integer")
    quit()
pong()
python pygame collision-detection pong
1个回答
0
投票

由于您不需要任何代码,因此以下是如何使用单词进行操作。

写一个名为ballHits()的函数。

传递给paddlecoords,球coords和球35半径的功能?作为radius

在这个新函数中,paddlecoords定义了一个矩形。代码需要检查Ball的边缘是否在此矩形内。

实现这一点的一种简单方法是计算出围绕球的矩形(正方形)的坐标。由于球是从中心涂上的,因此大致为:

[ coords.x - radius,  coords.y - radius,  2 * radius, 2 * radius ]
# the [ x, y, width, height] of a square covering a circle

使用PyGame的rect类,确定你的两个矩形是否重叠。

实现此目的的一种非简单方法是预先生成形成球的圆的边缘像素列表。也许使用Mid-Point Circle Algorithm之类的东西,以(0,0)为中心,给你一个你可以用当前Ball坐标调整的点数列表。

使用桨状矩形和PyGame的rect类确定当偏移到当前球位置时这些点中的任何一个是否与桨碰撞。这将为您提供真正的碰撞,而不是近似,并且可以更好地进行角落碰撞。首先用上面的方法检查粗略碰撞可能会更快,然后检查许多圆点。

如果代码确定存在冲突,则从函数返回True,否则返回False

在主代码中,调用此函数,并对返回的结果执行操作。

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