栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么我的碰撞测试总是返回'true',为什么图像矩形的位置总是错误(0,0)?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么我的碰撞测试总是返回'true',为什么图像矩形的位置总是错误(0,0)?

pygame.Surface.get_rect.get_rect()
返回具有
Surface 对象大小的矩形,但是由于 Surface 对象没有位置,因此它返回始终以(0,0)开始的矩形。
Surface放置在
blit
显示器上的某个位置。

您必须通过关键字参数来设置矩形的位置,例如:

self.rect = self.image.get_rect(topleft = (self.x, self.y))

或对虚拟属性的分配(请参阅参考资料

pygame.Rect
),例如:

self.rect = self.image.get_rect()self.rect.topleft = (self.x, self.y)

绝对没有必要添加一些额外的属性

self.x
self.y
。请改用矩形的位置。例如:

class Ball(pygame.sprite.Sprite):    def __init__(self):        pygame.sprite.Sprite.__init__(self)        self.image = pygame.image.load("ball.png")        self.rect = self.image.get_rect(topleft = (280, 475))        self.col = False    def update(self):        gameDisplay.blit(self.image, self.rect)    def test_collisions(self,sprite):        self.col = pygame.sprite.collide_rect(self,sprite)class Obstacle(pygame.sprite.Sprite):    def __init__(self):        pygame.sprite.Sprite.__init__(self)        self.image = pygame.image.load("obstacle.png")        self.time = pygame.time.get_ticks()        self.rect = self.image.get_rect(topleft = (1000, 483))    def change_x(self):        self.time = pygame.time.get_ticks()        self.rect.x = -(self.time/5) + 800    def update(self):        gameDisplay.blit(self.image, self.rect)

进一步注意,如果使用和调用(使用包含的sprite的和属性来绘制它们),则可以

Ball.update()
分别摆脱方法
Obstacle.update()
(可以删除它们)。例如:
pygame.sprite.Group
.draw()
.image``.rect

obstacle = Obstacle()ball = Ball()      all_sprites = pygame.sprite.Group([obstacle, ball])while not crashed:    # [...]    gameDisplay.fill((255,255,255))    all_sprites.draw(gameDisplay)    pygame.display.flip()    clock.tick(1000)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号