首页 文章

使用Sprite碰撞追溯-AttributeError:'Sprite' object没有属性'rect'

提问于
浏览
0

我是新手使用pygame,所以请原谅我可能正在犯的新手错误:)

我正在制作一个游戏,用户操作一辆汽车,并且必须躲避在地面上随意跑动的警车 . 我正在尝试使用 col=pygame.sprite.spritecollide(carImg,hit_list,False) ,其中 hit_list 是一辆警车,而且它是用户操作的汽车 . 这是代码的一部分; `

surface.blit(bg,(0,0))
    hit_list=pygame.sprite.Group()
    #player=pygame.sprite.Group()
    #player.add(carImg)
    hit_list.add(pCar)
    hit_list.add(pCarT)
    hit_list.add(pCarTH)
    hit_list.add(pCarF)

    hit_list.update()
    player.update()

    col=pygame.sprite.spritecollide(carImg,hit_list,False)
    if col==True:
        lost(h,j)`

你可以看到我在sprite.Group(播放器)中尝试了carImg(用户操作的汽车),但这也调用了回溯 .

这是我从运行代码得到的Trace

Traceback (most recent call last):
  File "C:\Users\Ali\Documents\snakey things\4carGame - Copy.py", line 133, in <module>
    col=pygame.sprite.spritecollide(carImg,hit_list,False)
  File "C:\Python27\lib\site-packages\pygame\sprite.py", line 1345, in spritecollide
    if spritecollide(s.rect):
AttributeError: 'Sprite' object has no attribute 'rect'

我做错了什么,以便碰撞不起作用?我该如何解决这个问题?

非常感谢Zat

2 回答

  • 1

    carImg 没有 rect 属性 .

    来自documentation

    要查找碰撞,Sprite必须分配Surface.rect属性 .

  • -1

    你必须为你在imageload之后声明的每个图像/精灵创建一个矩形,如:

    self.carImg = transform.scale(image.load('carImg.jpg').convert(),(100,200))
    carImg.rect = self.carImg.get_rect()
    
    self.pcarImg = transform.scale(image.load('pcarImg.jpg').convert(),(100,200))
    pcarImg.rect = self.carImg.get_rect()
    

相关问题