Прыжки создают дистанцию ​​между человеком и полом Pygame - PullRequest
1 голос
/ 14 марта 2019

Полный код:

import glob
import pygame
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (100, 40)

class Man(pygame.sprite.Sprite):
    # just taking random image to get height and width after trans scale to be able to crop later (see lines 23/36)
    idle_images_list = glob.glob(r"C:\Users\aviro\Desktop\מחשבים\python projects\platform game\animation\fighter\PNG\PNG Sequences\Firing"+'\*')
    random_image = pygame.image.load(idle_images_list[0])
    new_img_width = int(random_image.get_width()/2.5)
    new_img_height = int(random_image.get_height()/2.5)
    random_image_after_crop = random_image.subsurface((70, 35, new_img_width-125, new_img_height-45))
    # to be able to use needed images indexes

    # getting idle animations list
    right_idle_list = []
    left_idle_list = []
    for images in idle_images_list:
        img = pygame.image.load(images)
        wid = img.get_width()
        hei = img.get_height()
        img = pygame.transform.scale(img, (int(wid/2.5), int(hei/2.5)))
        img = img.subsurface((70, 35, new_img_width-125, new_img_height-45))
        right_idle_list.append(img)
        left_idle_list.append(pygame.transform.flip(img, True, False))

    # getting movement animations list
    walk_animation_list = glob.glob(r"C:\Users\aviro\Desktop\מחשבים\python projects\platform game\animation\fighter\PNG\PNG Sequences\Run Firing"+'\*')
    walk_right_list = []
    walk_left_list = []
    for files in walk_animation_list:                          # setting the animation list
        img = pygame.image.load(files)
        wid = img.get_width()
        hei = img.get_height()
        img = pygame.transform.scale(img, (int(wid/2.5), int(hei/2.5)))     # chaging scale
        img = img.subsurface((70, 35, new_img_width-125, new_img_height-45))
        walk_right_list.append(img)
        walk_left_list.append(pygame.transform.flip(img, True, False)) # mirror list

    def __init__(self, x, y,):
        super(Man, self).__init__()
        self.walk_left_list = Man.walk_left_list
        self.walk_right_list = Man.walk_right_list
        self.width = Man.new_img_width
        self.height = Man.new_img_height
        self.hitbox = (x+55, y+35, self.width-125, self.height-45) # nothing special on those num, just Trial and error
        self.rect = Man.random_image_after_crop.get_rect()
        self.rect.x = x
        self.rect.y = y

def game_redraw():   # print things in end for main loop
    global right
    global left
    screen.blit(bg_image, (0, 0))
    if right:
        screen.blit(man.walk_right_list[frame_count//3], (man.rect.x, man.rect.y))
    elif left:
        screen.blit(man.walk_left_list[frame_count//3], (man.rect.x, man.rect.y))
    else:
        if last_action == "right":
            screen.blit(man.right_idle_list[frame_count//13], (man.rect.x, man.rect.y))
        if last_action == "left":
            screen.blit(man.left_idle_list[frame_count//13], (man.rect.x, man.rect.y))
        else:                                                                   # just for the first move
            screen.blit(man.right_idle_list[frame_count//13], (man.rect.x, man.rect.y))
    pygame.draw.rect(screen, RED, man.rect, 4)
    pygame.display.flip()
    right = False
    left = False

def input_process(key):
    global right
    global left
    global last_action
    global man
    global frame_count
    global is_jump
    global neg
    global jump_count
    #
    if is_jump:
        if jump_count >= -10: # check if jumping
            if jump_count < 0:
                neg = -1
            man.rect.y -= (jump_count ** 2) * neg * 0.5
            jump_count -= 1
        else:
            neg = 1
            is_jump = False
    #
    if key[pygame.K_RIGHT] and man.rect.right + speed < w:
        if left:
            frame_count = 0
        right = True
        left = False
        last_action = "right"
        man.rect.x += speed
    #
    if key[pygame.K_LEFT] and man.rect.left + speed > 0:
        if right:
            frame_count = 0
        right = False
        left = True
        last_action = "left"
        man.rect.x -= speed
    #
    if not is_jump:
        if key[pygame.K_UP]:
            jump_count = 10
            is_jump = True

w = 1728
h = 972
pygame.init()
RED = (255, 0, 0)
images_folder = r'C:\Users\aviro\Desktop\מחשבים\python projects\platform game\images'+'\\'
bg_image = images_folder+"background.png"  # setting background image
ground_height = h-143    # the high of the image ground
man = Man(200, ground_height)
man.rect.bottom = ground_height
clock = pygame.time.Clock()
Refresh_Rate = 54
speed = 5
right = False
left = False
frame_count = 0
finish = False
last_action = ""
# jumping ver
is_jump = False
jump_count = 10
neg = 1
#
screen = pygame.display.set_mode((w, h))
bg_image = pygame.image.load(bg_image).convert()    # can do convert only after setting surface.
# main loop
while not finish:
    if frame_count >= 51:
        frame_count = 0
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            finish = True
    key = pygame.key.get_pressed()
    input_process(key)
    game_redraw()
    frame_count += 1
    clock.tick(Refresh_Rate)

Я пытаюсь создать простую игру со стрельбой на платформе, используя модуль pygame.Все отлично работает, кроме прыжков.Смотрите в строке 88. Игрок прыгает как парабола х ^ 2.Я добавил * 0.5 в конце строки, чтобы игрок прыгал медленнее и ниже, но когда я это делаю, это то, что произошло.

Перед прыжком:

enter image description here

После прыжка:

enter image description here

Посмотри на вторую картинку.Есть расстояние между полом и игроком.Когда убираю * 0.5 все работает нормально.Почему?

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