0
나는 플레이어 캐릭터와 대조하여 여러 스프라이트에 충돌 검사를 처리하려고합니다. 다음은 관련 코드입니다. Enemy
클래스는 이미지로 표시되는 새로운 스프라이트를 만들고 Character
클래스는 플레이어가 제어 할 수있는 스프라이트를 제외하고 비슷합니다. 다음은 프로젝트에서 잘라낸 관련 코드입니다.같은 유형의 여러 스프라이트에 대한 충돌 감지 검사는 어떻게 처리합니까?
self.all_sprites_list = pygame.sprite.Group()
sprite = Character(warrior, (500, 500), (66, 66))
enemies = []
for i in range(10):
enemy = Enemy("evilwizard")
enemies.append(enemy)
self.all_sprites_list.add(enemy)
self.all_sprites_list.add(sprite)
class Enemy(pygame.sprite.Sprite):
# This class represents the types of an enemy possible to be rendered to the scene
def __init__(self, enemy_type):
super().__init__() # Call sprite constructor
# Pass in the type of enemy, x/y pos, and width/height (64x64)
self.image = pygame.Surface([76, 76])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(10, 1150) # random start
self.rect.y = random.randrange(10, 590) # random start
self.speed = 2
self.move = [None, None] # x-y coordinates to move to
self.image = pygame.image.load(FILE_PATH_ENEMY + enemy_type + ".png").convert_alpha()
self.direction = None # direction to move the sprite`
class Character(pygame.sprite.Sprite):
def __init__(self, role, position, dimensions):
"""
:param role: role instance giving character attributes
:param position: (x, y) position on screen
:param dimensions: dimensions of the sprite for creating image
"""
super().__init__()
# Call the sprite constructor
# Pass in the type of the character, and its x and y position, width and height.
# Set the background color and set it to be transparent.
self.image = pygame.Surface(dimensions)
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.image = pygame.image.load(FILE_PATH_CHAR + role.title + ".png").convert_alpha()
# Draw the character itself
# position is the tuple (x, y)
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = position
self.attack = role.attack
self.health = role.health
self.title = role.title
에 대한 문서를 참조()'self.image = pygame.Surface()'를 사용하는 것은 의미가 없다. – furas
스프라이트가 움직일 때마다 새로운 위치는 다른 모든 기존 스프라이트와 비교하여 점검되어야한다. 침입이 발생합니다. – martineau
@martineau ive는'Character' 클래스의 이동 메소드를 얻었고 이동을 허용하기 전에'self.rect.x'와'self.rect.y'가 벽의 경계 근처에 있는지 확인합니다. 적 클래스에는 무작위 움직임을 만드는 로밍 메서드가 있습니다. 그 영역에서 수행해야합니까? – timoxazero