1

我正在制作一个游戏,如果锯子撞到玩家然后它就会死掉,但是当我让锯子弹回墙壁时,它就colliderect不起作用了。

这是我的代码:

import pygame
from pygame import draw
from pygame import Rect
pygame.init()

width = 1200
height = 700
screen = pygame.display.set_mode([width, height])

boss = pygame.image.load("C:/Users/Thien Truong/Downloads/Ninja.png")
bossx = 425 
bossy = 10
def drawBoss():
    screen.blit(boss,(bossx,bossy))

player = pygame.image.load("C:/Users/Thien Truong/Desktop/Player.png").convert()
playerrect = player.get_rect()
playerx = 575
playery = 625
playerspeed = 5

def drawPlayer():
    screen.blit(player,(playerx,playery))

circleX = 100
circleY = 100
radius = 10

saw = pygame.image.load("C:/Users/Thien Truong/Downloads/Saw3.png")
sawrect = saw.get_rect()
speed = [7, 7]
 
running = True
clock = pygame.time.Clock()
angle = 1
Bar = 0
rect_x = 50
rect_y = 50
 
rect_change_x = 2
rect_change_y = 2
while running:
    Bar += 0.04
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        if playery >= 0:
            playery -=  playerspeed
        else:
            playery -= 0
    if keys[pygame.K_DOWN]:
        if playery <= 650:  
            playery += playerspeed
        else:
            playery -= 0
    if keys[pygame.K_LEFT]:
        if playerx >= 0:
            playerx -=  playerspeed
    if keys[pygame.K_RIGHT]:
        if playerx <= 1145:
            playerx += playerspeed
        else:
            playery -= 0

    screen.fill([0,0,0])
    drawBoss()
    rect_x += rect_change_x
    rect_y += rect_change_y
 

    if rect_y > 650 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 1150 or rect_x < 0:
        rect_change_x = rect_change_x * -1
    balls = pygame.transform.rotate(saw,angle)
    angle += 1
    screen.blit(saw, (rect_x,rect_y))
    if sawrect.colliderect(playerrect):
        print("d")
    drawPlayer()
    pygame.draw.rect(screen, (0, 100, 255), (1175, 150, 20, 475), 3)
    pygame.draw.rect(screen,(0,255,0),(1175, 150, 20, Bar))
    if Bar > 475:
        pygame.quit()
    pygame.display.flip()
pygame.quit()

锯弹跳的部分:

    rect_x += rect_change_x
    rect_y += rect_change_y

    if rect_y > 650 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 1150 or rect_x < 0:
        rect_change_x = rect_change_x * -1
    balls = pygame.transform.rotate(saw,angle)
    angle += 1

科里森:

    if playerrect.colliderect(sawrect):
        print("d")

我尝试运行,但即使锯子甚至不靠近播放器,它似乎也会继续打印。

请帮忙!

4

1 回答 1

0

pygame.Surface.get_rect.get_rect()返回一个具有Surface对象大小的矩形,该矩形始终从 (0, 0) 开始,因为Surface对象没有位置。Surface位于blit屏幕上的某个位置。矩形的位置可以由关键字参数指定。例如,可以使用关键字参数指定矩形的左上角topleftpygame.Rect这些关键字参数在返回之前应用于 的属性(请参阅pygame.Rect关键字参数的完整列表)。

在碰撞测试之前设置矩形的位置:

playerrect.topleft = (playerx, playery)
sawrect.topleft = (rect_x, rect_y)

if playerrect.colliderect(sawrect):
    print("d")
于 2021-08-20T06:07:12.637 回答