如何使用pygame制作简单但有效的Hitbox

我正在做我的第一场比赛,捉猫。我是pygame的新手,所以不要期望我太多。

这是简单的游戏,您需要单击一只​​猫。随着分数的提高,猫会更快。

我需要为那只猫做打击箱。有人可以帮忙吗?

这是代码:

    #IMPORTS FOR THE GAME
import pygame, sys
from pygame.locals import *
pygame.init()
#game speed settings
FPS = 5
fpsClock = pygame.time.Clock()
#Display settings
DISPLAY = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Catch the cat')
#background music settings
pygame.mixer.music.load('backmusic.wav')
pygame.mixer.music.play(-1, 0.0)
#COLORS
WHITE = (255, 255, 255)
AQUA = (0, 255, 255)
BLACK = (0, 0, 0)
HITBOXCOLOR = (0, 255, 255, 255)
#CAT IMAGE SETUP
catImg = pygame.image.load('cat.png')
catx = 10
caty = 20
direction = 'right'
# SCORE DISPLAY SETUP
fontObj = pygame.font.Font('freesansbold.ttf', 20)
score = 0
textSurfaceObj = fontObj.render(str(score), True, AQUA, BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (10, 10)
while True:
    DISPLAY.fill(WHITE)
    DISPLAY.blit(textSurfaceObj, textRectObj)
    if direction == 'right':
        catx += 5
        if catx == 300:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 300:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 20:
            direction = 'right'
    DISPLAY.blit(catImg, (catx, caty))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)
评论
  • 妾随
    妾随 回复

    Use pygame.Rect objects. You can get a rectangle with the size of the cat by get_rect from the cat surface. Set the position of the cat by the key word attribute topleft. Use the MOUSEBUTTONDOWN event and collidepoint() to test if the mouse is on the cat when it is clicked:

    while True:
        # [...]
    
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
            if event.type == pygame.MOUSEBUTTONDOWN:
                cat_rect = catImg.get_rect(topleft = (catx, caty))
                if cat_rect.collidepoint(event.pos):
                    print("hit")