Мой персонаж перестал прыгать в этом пигме, почему? - PullRequest
0 голосов
/ 25 июня 2018

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

#Imports

import pygame
import sys
import math

#Pygame Initialisation

pygame.init()
windowWidth=500
windowHeight=500
win = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption("ScreenShove WIP")

#Movement Initialisation ((c) means constant)

x=250       #X Position
y=434       #Y Position
dx=0        #Perceived Change in X
dy=0        #Perceived Change in Y
width=40    #Character Width (c)
height=60   #Character Height (c)
ax=3        #X axis acceleration (c)
ay=20       #Y axis acceleration (c)
xprev=0     #Previous X Position
yprev=0     #Previous Y Position
isJump=False#Is the sprite performing a jump?
dylock=0    #Counts the number of frames dy has been 0 in a jump
border=5    #Border size (c)

run = True
while run:

pygame.time.delay(20) #50 ish fps
#Add 1 indentation for all the following lines
#Exit Check

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False

#Get Keypresses

keys = pygame.key.get_pressed()

#Y Movement Decay

assumeddx=x-xprev   #Recalculates "dx" based on previous positions.
assumeddy=y-yprev   #Recalculates "dy" based on previous positions.
xprev=x             #Fixes "xprev" and "yprev" for the next frame.
yprev=y

if isJump == True:                                          #If the sprite is performing a jump:
    if keys[pygame.K_s] and y<windowHeight-height-border:   #If the "s" key is pressed:
        dy+=math.ceil(ay/2)                                 #Increase the change in Y by half the Y axis acceleration constant
    if assumeddy==0 or dy==0:                               #If the calculated or perceived change in Y is 0:
        if dylock>=2:                                       #If the change in Y is equal to 0 at least twice this jump:
            isJump=False                                    #Declare the sprite has finished performing a jump
            dylock=0                                        #Reset the counter
            dy=0                                            #Set the perceived change in Y to 0
        else:                                               #Otherwise:
            dylock+=1                                       #Increase the counter by 1
    dy+=1                                                   #Increase the perceived change in Y by 1.
else:                                                       #Otherwise:
    dy=0                                                    #Set the perceived chnage in Y to 0.

#X Movement Decay

if dx>0:                                                    #If the perceived change in X is positive:
    dx-=1                                                   #Reduce it by 1
if dx<0:                                                    #If the perceived change in X is negative:
    dx+=1                                                   #Increase it by 1

#User Movement Changes

if keys[pygame.K_a] and x>=dx+border and dx>-10:                #If the "a" key is pressed and the sprite is in a valid position and the change in X exceeds -10:
    dx-=ax                                                      #Reduce the change in X by the X axis acceleration constant
elif keys[pygame.K_d] and x<windowWidth-width-border and dx<10: #If the "d" key is pressed and the sprite is in a valid position and the change in X does not exceed 10:
    dx+=ax                                                      #Increase the change in X by the X axis acceleration constant
if keys[pygame.K_w]:                                            #If the "w" key is pressed:
    if y >= dy+border and isJump==False and jumplock==False:    #If the sprite is in a valid position, is not performing a jump already and the jump key isn't locked:
        dy-=ay                                                  #Decrease the change in Y by the Y axis acceleration constant
        isJump = True                                           #Declare the sprite is performing a jump.
    jumplock=True                                               #Lock the jump key.
else:                                                           #Otherwise:
    jumplock=False                                              #Unlock the jump key.

#Border Fix for Velocity

if dx<0:                                                        #If the change in X is positive
    if x>=-dx+border:                                           #If the sprite is in a valid position
        x+=dx                                                   #Increase the X position by the change in X
    else:                                                       #Otherwise:
        dx=0                                                    #Set the change in X to 0
        x=border                                                #Set the X position to the nearest valid X position
if dx>0:
    if x<=windowWidth-width-border:
        x+=dx
    else:
        dx=0
        x=windowWidth-width-border
if dy>0:
    if y<=windowHeight-height-border:
        y+=dy
    else:
        dy=0
        y=windowHeight-height-border

#Border Fix for Position

if x<0+border:
    x=border
if x>windowWidth-width-border:
    x=windowWidth-width-border
if y>windowHeight-height-border:
    y=windowHeight-height-border

#Debugging

print("P:",x,y)
print("V:",dx,dy)
print("Jumping:",str(isJump))
print("Jump Locked:",str(jumplock))

#Draw to Screen

win.fill((0,0,0))
pygame.draw.rect(win, (0, 200 ,0), (x,y,width,height))
pygame.display.update()

#No more indentations

#Exit

pygame.quit()
sys.exit()

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

P: 250 434
V: 0 0
Jumping: False
Jump Locked: False
P: 250 434
V: 0 -20
Jumping: True
Jump Locked: True
P: 250 434
V: 0 -19
Jumping: True
Jump Locked: True
P: 250 434
V: 0 -18
Jumping: True
Jump Locked: False
P: 250 435
V: 0 1
Jumping: False
Jump Locked: False
P: 250 435
V: 0 0
Jumping: False
Jump Locked: False

P означает положение.

V означает скорость или изменение положения.

Оба даны как "X Y".

Прыжки это логическое «isJump» и Jump Locked - это логический «прыжок».

1 Ответ

0 голосов
/ 25 июня 2018

Вместо этого:

if dy>0:
    if y<=windowHeight-height-border:
        y+=dy
    else:
        dy=0
        y=windowHeight-height-border

Я должен был сделать это:

if y<=windowHeight-height-border:
    y+=dy
elif dy>0:
    dy=0
    y=windowHeight-height-border

Потому что dy не всегда является положительным значением (ну никак не Том).

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

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