Столкновение с прямоугольником Pygame не работает - PullRequest
0 голосов
/ 17 мая 2019

В своей игре я пытаюсь создать искусственных врагов, которые будут летать или двигаться в другую сторону, касаясь края платформы, но проблема, с которой я сталкиваюсь, заключается в том, что это столкновение с прямоугольником, похоже, не работает

Я пытался использовать столкновение с прямоугольником, которое проверяет, равна ли левая сторона прямоугольника правой части платформы справа от прямоугольника, тогда противник либо улетит вверх на другую платформу, либо переключит направление.

log_pic = pygame.image.load("C:/knuckles_pictures/log.png").convert_alpha()
platform_pic = pygame.image.load("C:/knuckles_pictures/ground.jpg").convert_alpha()
class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, background, a, b):
        self.xpos = x
        self.ypos = y
        super().__init__()
        self.picture = background
        self.picture = pygame.transform.scale(self.picture, (a, b))
        self.rect = self.picture.get_rect()
        self.rect.x = self.xpos
        self.rect.y = self.ypos

    def draw(self):
        screen.blit(self.picture, (self.xpos, self.ypos))



robot_pic = pygame.image.load("C:/knuckles_pictures/robo_knuckles.gif").convert_alpha()
class Robot_knuckles(pygame.sprite.Sprite):
    def  __init__(self, x, y, picture, direction, start_speed):
        self.xpos = x
        self.ypos = y
        self.speed_y = 0
        self.speed_x = start_speed
        self.direction = direction
        self.previous_direction = self.direction
        self.picture = picture
        self.picture_tag = "robot knuckles"
        self.on_ground = False
        self.under_platform = False
        self.fuel = 100
        super().__init__()
        self.GRAVITY = 0.9
        self.action_lock = False
        self.picture = pygame.transform.scale(self.picture, (250, 200))
        self.rect = self.picture.get_rect()
        self.rect.x = self.xpos
        self.rect.y = self.ypos
        self.flying = False

    def update(self):
        if self.fuel == 0 or self.on_ground == False:
            self.speed_y += self.GRAVITY
            self.xpos += self.speed_x
            self.ypos += self.speed_y
            self.flying == False
        else:
            self.xpos += self.speed_x
            self.ypos += self.speed_y

        if self.ypos >= 620:
            self.on_ground = True


        if self.on_ground == True:
            self.speed_y = 0
            self.fuel = 100
            self.flying = False
            self.xpos += self.speed_x 
            self.ypos += self.speed_y


        self.rect.x = self.xpos
        self.rect.y = self.ypos


    def fly(self):
        if self.on_ground:
            self.on_ground = False
            self.speed_y = -3


    def turn_around(self, direction):
            if self.speed_x < 0:
                self.direction = "left"

            elif self.speed_x > 0:
                self.direction = "right"

            if self.direction != self.previous_direction:#meaning you can only flip to the opposite side when you direction is not equal to you last direction
                self.picture = pygame.transform.flip(self.picture, True, False)
                self.previous_direction = self.direction


    def is_collided_with(self, sprite):
        return self.rect.colliderect(sprite.rect)


    def draw(self):
        screen.blit(self.picture, (self.xpos, self.ypos))



wood_platform = Platform(450, 500, platform_pic, 350, 100)
wood_platform_two = Platform(900, 150, platform_pic, 300, 70)
wood_platform_three = Platform(100, 150, platform_pic, 300, 70)
platforms.add(wood_platform)
platforms.add(wood_platform_two)
platforms.add(wood_platform_three)






while True:
[...]

if monster_spawner_lock == False:
        monster_spawner_lock = True
        choice_of_monster = random.randint(1, 40)
        direction_choice = random.randint(1, 2)

        if choice <= 2:
            if direction_choice == 1:#LEFT
                robot_knuckles = Robot_knuckles(random.randint(800, 1400), -60, robot_pic, "left", 0)
                enemies.add(robot_knuckles)

            elif direction_choice == 2:#RIGHT
                robot_knuckles = Robot_knuckles(random.randint(0, 600), -60, robot_pic, "right", 0)
                enemies.add(robot_knuckles)


    if monster_spawner_lock == True:
        spawn_another = random.randint(1, 500)
        if spawn_another == 1:
            monster_spawner_lock = False


for enemy in enemies:
        for platform in platforms:
            if enemy.rect.left > platform.rect.right:
                choice_of_action = random.randint(1, 2)
                if choice_of_action == 1:
                    enemy.speed_x = -4

                else:
                    enemy.fly()


            elif enemy.rect.right < platform.rect.left:
                choice_of_action = random.randint(1, 2)
                if choice_of_action == 1:
                    enemy.speed_x = 4

                else:
                    enemy.fly()
                    enemy.flying = True


    for enemy in enemies:
        if enemy.flying == True:
            enemy.fuel -= 1


    for enemy in enemies:
        happened = False
        for platform in platforms:
            if enemy.is_collided_with(platform) and enemy.speed_y > 0: #and enemy.under_platform == True:
                enemy.on_ground = True
                happened = True

        if happened == False:
            enemy.on_ground = False




    for enemy in enemies:
        if enemy.ypos <= 100:
            if enemy.direction == "left":
                enemy.speed_x = -4

            elif enemy.direction == "right":
                enemy.speed_x = 4


for enemy in enemies:
        enemy.update()


for enemy in enemies:
        enemy.draw()

Фактический результат заключается в том, что враг продолжает дрожать на определенной платформе, а затем, когда появляется множество других, уходят в центр и также начинают дрожать.

Вот диаграмма, чтобы помочь: meh

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...