我试图在pygame中创建一个赛车游戏。我希望它能在赛车离开赛道时减速。我曾尝试过通过另一个精灵来实现这一点,这个精灵是赛道的轮廓,当赛车接触到这个精灵时,它减速。这不起作用,我不知道为什么。有更好的方法来实现这一点吗?Img
是汽车图像Back
是赛道BackHit
是轮廓
我收到此错误代码:
追溯(最近调用最后调用):文件"C:\Users\Daniella\Desktop\Python\Games\game.py",第75行,在如果pygame. sprite. collide_mask(图像,回击):文件"C:\用户\丹妮拉\应用数据\漫游\Python\Python36\站点包\pygame\sprite.py",第1470行,在碰撞屏蔽中xoffset =右. rect [0]-左. rect [0]属性错误:"pygame.surface"对象没有属性"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()
2条答案
按热度按时间fjnneemd1#
这里有一个小例子,向您展示如何使用
pygame.mask.from_surface
和pygame.Mask.overlap
进行像素完美碰撞检测。要为背景或轨道创建蒙版,您需要创建一个额外的图像,让轨道或汽车应该减速的区域保持透明,然后检查汽车是否与轨道或外部区域碰撞。这里我检查绿色三角形是否与“轨道”(蓝线)碰撞,在您的游戏中,如果汽车没有与轨道碰撞,您将减速。
8qgya5xd2#
pygame.sprite.collide_mask
用于pygame.sprite.Sprite
对象。请改用mask_var.overlap(other_mask, offset)
。要计算两个遮罩之间的偏移量,请使用offset = [other_object_x - object_x, other_object_y - object_y]
。要获取图像的遮罩,请使用mask_var = pygame.mask.from_surface(image)
。