我正在嘗試在pygame中創建一個賽車遊戲。我想要這樣,當汽車離開賽道時,速度會減慢。我試圖通過讓另一個精靈是軌道輪廓,當汽車接觸到這個精靈,它會減速。這不起作用,我不知道爲什麼。有一個更好的方法嗎?pygame中的Sprite面具碰撞問題
Img
是汽車圖像
Back
是賽道
BackHit
是大綱
我收到此錯誤代碼:
Traceback (most recent call last): File "C:\Users\Daniella\Desktop\Python\Games\game.py", line 75, in if pygame.sprite.collide_mask(Img, BackHit): File "C:\Users\Daniella\AppData\Roaming\Python\Python36\site-packages\pygame\sprite.py", line 1470, in collide_mask xoffset = right.rect[0] - left.rect[0] AttributeError: 'pygame.Surface' object has no attribute 'rect'
這是代碼:
import pygame
Width = 800
Height = 600
Black = (0, 0, 0)
White = (255, 255, 255)
Red = (255, 0, 0)
Green = (0, 255, 0)
Blue = (0, 0, 255)
Yellow = (255, 255, 0)
BackColour = (198, 151, 107)
pygame.init()
GameDisplay = pygame.display.set_mode((Width, Height))
pygame.display.set_caption("A bit Racey")
Clock = pygame.time.Clock()
Img = pygame.image.load("download.png")
ImgWidth = 46
ImgHeight = 68
Img = pygame.transform.scale(Img, (ImgWidth, ImgHeight))
Back = pygame.image.load("back1.png")
BackWidth = Width*4
BackHeight = Height*4
Back = pygame.transform.scale(Back, (BackWidth, BackHeight))
BackHit = pygame.image.load("back1 hit1.png")
BackHitWidth = Width*4
BackHitHeight = Height*4
BackHit = pygame.transform.scale(BackHit, (BackHitWidth, BackHitHeight))
def Car():
GameDisplay.blit(Img, (400-ImgWidth/2, 300-ImgHeight/2))
def Background(X, Y):
GameDisplay.blit(Back, (X, Y))
def BackgroundHit(X, Y):
GameDisplay.blit(BackHit, (X, Y))
X = (Width*0.45)
Y = (Height*0.5)
XChange = 0
YChange = 0
Changer = 1
Crashed = False
while not Crashed:
for Event in pygame.event.get():
if Event.type == pygame.QUIT:
Crashed = True
elif Event.type == pygame.KEYDOWN:
if Event.key == pygame.K_LEFT:
Img = pygame.transform.rotate(Img, -90)
XChange = 5/Changer
elif Event.key == pygame.K_RIGHT:
Img = pygame.transform.rotate(Img, 90)
XChange = -5/Changer
elif Event.key == pygame.K_UP:
Img = pygame.transform.rotate(Img, 0)
YChange = 5/Changer
elif Event.key == pygame.K_DOWN:
Img = pygame.transform.rotate(Img, 180)
YChange = -5/Changer
if Event.type == pygame.KEYUP:
if Event.key == pygame.K_LEFT or Event.key == pygame.K_RIGHT:
XChange = 0
elif Event.key == pygame.K_UP or Event.key == pygame.K_DOWN:
YChange = 0
if pygame.sprite.collide_mask(Img, BackHit):
Changer = 2
Y += YChange
X += XChange
GameDisplay.fill(White)
BackgroundHit(X, Y)
Background(X, Y)
Car()
pygame.display.update()
Clock.tick(200)
pygame.quit()
quit()
'pygame.sprite.collide_mask'與'pygame.Sprite's不是'pygame.Surface's一起使用。你知道如何使用'pygame.Sprite'類嗎?如果沒有,請查看此[教程](http://programarcadegames.com/index.php?chapter=introduction_to_sprites&lang=en#section_13)。或者,您可以創建[來自曲面的遮罩](http://renesd.blogspot.com/2017/03/pixel-perfect-collision-detection-in.html)。 – skrx
我的意思是'pygame.sprite.Sprite'而不是'pygame.Sprite'。 – skrx