Как я могу заставить моих игроков прямо столкнуться со сторонами и низом моего врага? Pygame - PullRequest
4 голосов
/ 20 июня 2020
• 1000 1001 * VIDEo << как вы можете видеть на видео, любая помощь приветствуется. Мне просто нужно, чтобы мой прямоугольник не go бросал или go поднимался, когда я сталкиваюсь по сторонам </p>

моя часть столкновения


    playerman.isJump = False
    collide = False
    for platform in platforms:
        if playerman.rect.colliderect(platform.rect):
            collide = True
            playerman.isJump = False
            playerman.y = platform.rect.top - playerman.height + 1
            if playerman.rect.right > platform.rect.left and playerman.rect.left < platform.rect.left - playerman.width:
                playerman.x = platform.rect.left - playerman.width
            if playerman.rect.left < platform.rect.right and playerman.rect.right > platform.rect.right + playerman.width:
                playerman.x = platform.rect.right



нет изображений, только квадраты, вы можете протестировать код

import pygame,random

window = pygame.display.set_mode((800,800), pygame.NOFRAME)

# player factory
class player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.speed = 4
        self.fall = 0
        self.isJump = False
        self.jumpCount = 10
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

# player factory
class platform:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)


white = (255,255,255)
platform1 = platform(590,590,60,60,white)

platforms = [platform1]

# make the player
pink = (205,105,205)
playerman = player(300,300,60,60,pink)



# the game fps
clock = pygame.time.Clock()
FPS = 30

def keyevents():
    if keys[pygame.K_w]:
        playerman.y -= playerman.speed

    if keys[pygame.K_s]:
        playerman.y += playerman.speed

    if keys[pygame.K_d]:
        playerman.x += playerman.speed

    if keys[pygame.K_a]:
        playerman.x -= playerman.speed

    if keys[pygame.K_SPACE]:
        playerman.isJump = True



                
def jump():
    if playerman.isJump:
        if playerman.jumpCount >= -10:
            neg = 1
            if playerman.jumpCount < 0:
                neg = -1
            playerman.y -= playerman.jumpCount**2 * 0.5 * neg
            playerman.jumpCount -= 1
        else:
            playerman.isJump = False
            playerman.jumpCount = 10

    collide = False        # this makes the player fall down up to 
         # move the player
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        playerman.isJump = False
                    
        if playerman.rect.bottom >= 680:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 680 - playerman.height

        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0




# redraw the window
def redraw():
    playerman.draw()
    platform.draw()
# main loop
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runningggame = False

    # key event
    keys = pygame.key.get_pressed()

    # this is the key events
    keyevents()

    jump() # JUMP AND COLLISION on the grawn

    playerman.isJump = False
    collide = False
    for platform in platforms:
        if playerman.rect.colliderect(platform.rect):
            collide = True
            playerman.isJump = False
            playerman.y = platform.rect.top - playerman.height + 1
            if playerman.rect.right > platform.rect.left and playerman.rect.left < platform.rect.left - playerman.width:
                playerman.x = platform.rect.left - playerman.width
            if playerman.rect.left < platform.rect.right and playerman.rect.right > platform.rect.right + playerman.width:
                playerman.x = platform.rect.right





    window.fill((0,0,0))
    redraw()
    pygame.display.update()
pygame.quit()

Я просто ищу базовые c коллизии Я касаюсь своих врагов прямо влево и вправо и go внизу он не будет бросать, и если я столкнусь с ним сверху, он позволяет моему игроку стоять на нем

Ответы [ 2 ]

1 голос
/ 01 августа 2020

Чтобы скорость после столкновения была такой же, вы должны сделать self.speed = -self.speed, но вы также можете добавить настраиваемое значение скорости, чтобы ускориться еще больше, и вычесть еще больше, чтобы увеличить скорость после столкновения. (Это добавляет еще больше настроек скорости)

1 голос
/ 01 августа 2020

Наконец-то я нашел решение! Вот код, который позволяет всему работать правильно. Если хотите, я могу рассказать вам в чате о внесенных мною изменениях и о том, что они делают. Обратите внимание, что я запрограммировал это в Python 3, поэтому вам может потребоваться внести некоторые изменения, чтобы он работал в Python 2.

import pygame,random

window = pygame.display.set_mode((800,800), pygame.NOFRAME)

# player factory
class player:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.moveleft = True
        self.moveright = True
        self.color = color
        self.speed = 4
        self.fall = 0
        self.isJump = False
        self.jumpCount = 10
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)

# player factory
class platform:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.rect)


white = (255,255,255)
platform1 = platform(590,590,60,60,white)

platforms = [platform1]

# make the player
pink = (205,105,205)
playerman = player(300,300,60,60,pink)



# the game fps
clock = pygame.time.Clock()
FPS = 30

def keyevents():
    if keys[pygame.K_w]:
        playerman.y -= playerman.speed

    if keys[pygame.K_s]:
        playerman.y += playerman.speed

    if keys[pygame.K_d]:
        if playerman.moveright:
            playerman.x += playerman.speed    

    if keys[pygame.K_a]:
        if playerman.moveleft:
            playerman.x -= playerman.speed

    if keys[pygame.K_SPACE]:
        playerman.isJump = True



                
def jump():
    if playerman.isJump:
        if playerman.jumpCount >= -10:
            neg = 1
            if playerman.jumpCount < 0:
                neg = -1
            playerman.y -= playerman.jumpCount**2 * 0.5 * neg
            playerman.jumpCount -= 1
        else:
            playerman.isJump = False
            playerman.jumpCount = 10

    collide = False        # this makes the player fall down up to 
         # move the player
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        playerman.isJump = False
                    
        if playerman.rect.bottom >= 680:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 680 - playerman.height

        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0




# redraw the window
def redraw():
    playerman.draw()
    platform.draw()
# main loop
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runningggame = False

    # key event
    keys = pygame.key.get_pressed()

    # this is the key events
    keyevents()

    jump() # JUMP AND COLLISION on the grawn

    playerman.isJump = False
    collide = False
    for platform in platforms:
        if playerman.rect.colliderect(platform.rect):
            collide = True
            playerman.isJump = False
            if (platform.rect.collidepoint(playerman.rect.right, playerman.rect.bottom) or
                platform.rect.collidepoint(playerman.rect.left, playerman.rect.bottom)):
                playerman.y = platform.rect.top - playerman.height + 1
                playerman.moveright = True
                playerman.moveleft = True
            
            if (platform.rect.collidepoint(playerman.rect.right, playerman.rect.top) or
                platform.rect.collidepoint(playerman.rect.right, playerman.rect.bottom - 10)):
                playerman.moveright = False
            elif (platform.rect.collidepoint(playerman.rect.left, playerman.rect.top) or
                  platform.rect.collidepoint(playerman.rect.left, playerman.rect.bottom - 10)):
                playerman.moveleft = False
        else:
            playerman.moveright = True
            playerman.moveleft = True
                
                

    window.fill((0,0,0))
    redraw()
    pygame.display.update()
pygame.quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...