Pygame Platformer Sprite Collisions работают только в одном направлении - PullRequest
0 голосов
/ 17 апреля 2020

Я сейчас работаю над простым школьным проектом, где я пишу платформер. Моя проблема в том, что столкновения между моим игроком и моей платформой (-ами) проверяются одна за другой, поэтому, если я сначала проверяю X Collision, столкновения по сторонам платформ будут работать нормально, но как только я перееду, мой персонаж будет телепортирован в сторону платформы, потому что гравитация притягивает меня к платформе, и я двигаюсь влево или вправо, поэтому программа думает, что я ударю по платформе сбоку, и устанавливает игрока прямо на сторону Платформа. То же самое происходит, если я сначала проверяю X Collision, но с коллизиями по бокам платформ не работает.

Есть ли способ обойти это, поэтому мои коллизии работают как в Mario-like Игра? Я попробовал несколько вещей и удалил расчет с помощью трения и ускорения для плавного движения, но мне кажется, что ничего не работает.

Вот мой полный код:

import random
import os

WIDTH = 640
HEIGHT = 600
FPS = 60
TITLE = "Game"

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder,"textures")

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
BLUE = (0,0,255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_GRAV = 0.5

PGROUND = "dirtplatform.png"
PBLOCK = "dirt.png"

PLATFORM_LIST = [(0, HEIGHT - 64, PGROUND),
                 (WIDTH / 2, HEIGHT / 2, PBLOCK),
                 (WIDTH / 4, HEIGHT / 4, PBLOCK)]

vec = pygame.math.Vector2

class Player(pygame.sprite.Sprite):
    def __init__(self, game):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        self.image = pygame.image.load(os.path.join(img_folder,"player.png")).convert()
        self.image.set_colorkey((130,255,230))
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH/2,HEIGHT/2)
        self.vel = vec(0,0)

    def jump(self):
        self.rect.y += 1
        hits = pygame.sprite.spritecollide(self, self.game.platforms, False)
        self.rect.y -= 1
        if hits:
            self.vel.y = -20

    def collision(self, direction):
        if direction == 'x':
           hits = pygame.sprite.spritecollide(self, self.game.platforms, False)
           if hits:
                print("Hit x")
                if self.vel.x > 0:
                    self.rect.right = hits[0].rect.left
                if self.vel.x < 0: 
                    self.rect.left  = hits[0].rect.right   
                self.vel.x = 0
        if direction == 'y':
            hits = pygame.sprite.spritecollide(self, self.game.platforms, False)
            if hits:
                print("Hit y")
                if self.vel.y > 0:
                    self.rect.bottom = hits[0].rect.top 
                if self.vel.y < 0: 
                    self.rect.top= hits[0].rect.bottom
                self.vel.y = 0

    def update(self):
        self.acc = vec(0,PLAYER_GRAV)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.vel.x = -5
        elif keys[pygame.K_RIGHT]:
            self.vel.x = 5

        self.rect.x = self.rect.x + self.vel.x
        self.rect.y = self.rect.y + self.vel.y

        self.collision('x')
        self.collision('y')



        print("vel",self.vel)
        print("rectX",self.rect.x)
        print("rectY",self.rect.y)

        self.vel.y = self.vel.y + PLAYER_GRAV

        self.vel.x = 0

class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, image):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder,image)).convert()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y


class Game:
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption(TITLE)
        self.clock = pygame.time.Clock()
        self.running = True


    def new(self):
        self.all_sprites = pygame.sprite.Group()
        self.platforms = pygame.sprite.Group()
        self.player = Player(self)
        self.all_sprites.add(self.player)
        for plat in PLATFORM_LIST:
            p = Platform(*plat)
            self.all_sprites.add(p)
            self.platforms.add(p)
        self.run()

    def run(self):       
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def collision(self):
        if self.player.vel.y > 0 and pygame:
            hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
            if hits:
                self.player.pos.y = hits[0].rect.top
                self.player.vel.y = 0

    def update(self):
        self.all_sprites.update()
        keys = pygame.key.get_pressed()
        if self.player.rect.right >= WIDTH-100:
            self.player.rect.x = WIDTH - 110
            for plat in self.platforms:
                plat.rect.right -= abs(self.player.vel.x)

        if self.player.rect.left <= 100:
            self.player.rect.x = 110
            for plat in self.platforms:
                plat.rect.right += abs(self.player.vel.x)

    def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    self.player.jump()

    def draw(self):
        self.screen.fill(BLACK)
        self.all_sprites.draw(self.screen)
        pygame.display.flip()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass

g = Game()
g.show_start_screen()
while g.running:
    g.new()
    g.show_go_screen

pygame.quit()

Примечание: dirtplatform.png представляет собой основание игры, а dirt.png - это блок, на который игрок должен уметь прыгать

1 Ответ

0 голосов
/ 17 апреля 2020

Столкновения - это тяжело, кажется, не существует идеального способа сделать это, и каждый раз, когда я делаю это, они меняются каждый раз. Сказав это, похоже, это очень хорошо работает с двумя минутами тестирования, которые я только что сделал:

def collision(self):
    for platform in self.game.platforms: #check every platform
        if self.rect.colliderect(platform.rect): #if the two rects collided
            if self.rect.right <= platform.rect.left + self.vel.x:
                self.rect.right = platform.rect.left   
                self.vel.x = 0
            if self.rect.left >= platform.rect.right + self.vel.x:
                self.rect.left = platform.rect.right   
                self.vel.x = 0 
            if self.rect.bottom <= platform.rect.top + self.vel.y:
                self.rect.bottom = platform.rect.top  
                self.vel.y = 0  
            if self.rect.top >= platform.rect.bottom + self.vel.y:
                self.rect.top = platform.rect.bottom 
                self.vel.y = 0
...