如何围绕矩形居中放置一个表面(子表面)?(缩放的精灵Hitbox 碰撞矩形)

如何围绕矩形居中放置一个表面(子表面)?(缩放的精灵Hitbox 碰撞矩形),第1张

如何围绕矩形居中放置一个表面(子表面)?(缩放的精灵Hitbox /碰撞矩形)

如果您想要缩放的碰撞矩形/点击框,则需要给精灵一个第二矩形(我

hitbox
在这里称呼它)。您必须这样做,因为pygame会在的左上角坐标处涂抹图像/表面
self.rect
。因此,第一个rect
self.rect
用作blit位置,并且
self.hitbox
用于碰撞检测。

您还需要为碰撞检测定义一个自定义的回调函数,您必须将其

pygame.sprite.spritecollide
作为第四个参数传递给该函数。

def collided(sprite, other):    """Check if the `hitbox` rects of the two sprites collide."""    return sprite.hitbox.colliderect(other.hitbox)collided_sprites = pg.sprite.spritecollide(player, enemies, False, collided)

这是一个完整的示例(

self.rect
s是绿色矩形,
self.hitbox
es是红色矩形):

import pygame as pgfrom pygame.math import Vector2class Entity(pg.sprite.Sprite):    def __init__(self, pos, *groups):        super().__init__(*groups)        self.image = pg.Surface((70, 50))        self.image.fill((0, 80, 180))        self.rect = self.image.get_rect(center=pos)        # A inflated copy of the rect as the hitbox.        self.hitbox = self.rect.inflate(-42, -22)        self.vel = Vector2(0, 0)        self.pos = Vector2(pos)    def update(self):        self.pos += self.vel        self.rect.center = self.pos        self.hitbox.center = self.pos  # Also update the hitbox coords.def collided(sprite, other):    """Check if the hitboxes of the two sprites collide."""    return sprite.hitbox.colliderect(other.hitbox)def main():    screen = pg.display.set_mode((640, 480))    clock = pg.time.Clock()    all_sprites = pg.sprite.Group()    player = Entity((300, 200), all_sprites)    enemies = pg.sprite.Group(        Entity((100, 250), all_sprites),        Entity((400, 300), all_sprites),        )    done = False    while not done:        for event in pg.event.get(): if event.type == pg.QUIT:     done = True elif event.type == pg.MOUSEMOTION:     player.pos = event.pos        all_sprites.update()        # Pass the custom collided callback function to spritecollide.        collided_sprites = pg.sprite.spritecollide( player, enemies, False, collided)        for sp in collided_sprites: print('Collision', sp)        screen.fill((30, 30, 30))        all_sprites.draw(screen)        for sprite in all_sprites: # Draw rects and hitboxes. pg.draw.rect(screen, (0, 230, 0), sprite.rect, 2) pg.draw.rect(screen, (250, 30, 0), sprite.hitbox, 2)        pg.display.flip()        clock.tick(30)if __name__ == '__main__':    pg.init()    main()    pg.quit()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5639764.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存