Как заставить прямоугольник оставаться на движущейся линии в python

#python #pygame

#python #pygame

Вопрос:

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

 import random, time
import pygame, sys
from random import randint
from pygame.locals import *
pygame.init()



#fall sem teiknar veggi lóðrétta og lárétta
def teikna_vegg(x_veggur):
    fjoldi=len(x_veggur)
    for i in range (0,fjoldi):
        pygame.draw.line(DISPLAYSURF, GREEN, (x_veggur[i][0], x_veggur[i][1]),(x_veggur[i][2],x_veggur[i][3]), veggur_breidd)


def haetta(b):      #lokatexti sem kemur þegar forritið er búið
    text = font.render(b, True, WHITE)
    text_rect = text.get_rect()
    text_x = DISPLAYSURF.get_width() / 2 - text_rect.width / 2
    text_y = DISPLAYSURF.get_height() / 2 - text_rect.height / 2
    DISPLAYSURF.blit(text, [text_x, text_y])
    pygame.display.flip()
    time.sleep(5)
    quit()

# setur upp gluggann
DISPLAYSURF = pygame.display.set_mode((400, 400), 0, 32)    #búa til glugga
pygame.display.set_caption('Lokaverkefni')   #nafn á glugga


FPS = 60 # rammar á sek (hraði)
fpsClock = pygame.time.Clock()

# Litir
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0,255,0)
BLUE = ( 0, 0, 255)
YELLOW = (255,255,0)
litur=BLACK

font = pygame.font.Font(None, 36)   # Leturgerðin sem við notum og stærðin er 36



#upphafshnit kassa


kassi_staerd=10
veggur_breidd=10

#hradi á punkt
hradix=0
hradiy= -0.4



hoppa = False
hoppteljari = 0

# upphafshnit geimvera á y ás
gx=random.randrange(0,350)
gx2 = gx 50
gy = 360

x=gx
y=345

x_veggur_speed = -0.4


x_veggur=[[gx,gy,gx2,gy]]



while True: # main game loop
    DISPLAYSURF.fill(RED)
    teikna_vegg(x_veggur)   #Teiknar lárétta veggi
    #hreyfir svarta punktinn
    x =hradix
    y =hradiy





        #takkar til að sjtóra kassa
    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT):
                hradix=-1
            elif (event.key == K_RIGHT):
                hradix=1
            elif (event.key == K_SPACE):
                hoppa=True
            elif event.key == K_ESCAPE:
                pygame.qiuit()
                sys.exit()
        elif event.type == KEYUP:
            if (event.key == K_LEFT ):
                hradix=0
            elif (event.key == K_RIGHT ):
                hradix=0
            elif event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()




        #Hoppið (Jump)
    if hoppa==True:      #ef hann er að hoppa
        hoppteljari =1
        if hoppteljari<20:  #ef teljari er minni en 20
            y-=2                #þá hækkar hann um 2 á skjánum (mínus tala færir hann ofar)
        elif hoppteljari>20 and hoppteljari<24:     # ef teljari er á bilinu 20 - 24
            y =0            #þá hreyfist hann ekkert er kyrr í smá stund
        elif hoppteljari>24:    # ef teljari er hærri en 24 (þá er hann á leiðinni niður)
            y =1    #þá færist hann 1 niður



    #hreyfir svarta punktinn
    x =hradix


    #I think this needs to be changed
    #Athugar hvort að punktur hittir láréttan vegg 
    fjx=len(x_veggur)
    if hoppteljari==0:  #Ef hann er ekki að hoppa þá lækkar hann um 2 ef hann er ekki á vegg
        y  =2   #punktur lækkar
    for i in range (0,fjx):     # fer í gegnum listan með veggjunum
        #   athugar hvort svarti punkturinn sé á vegg
        if y>x_veggur[i][1]-14 and y<x_veggur[i][3]-12 and x>=x_veggur[i][0]-10 and x<=x_veggur[i][2] 1:
            y -=2 #tekur til baka lækkunina sem var gerð 3 línum ofar
            hoppa=False     #Stoppar hoppið ef hann lendir á vegg
            hoppteljari=0   #núllstillir teljarann fyrir hoppið




    #This code also needs to be changed    
    y =hradiy
    x_veggur[i][1]  = x_veggur_speed
    x_veggur[i][3]  = x_veggur_speed

    fjx=len(x_veggur)
    if x_veggur[i][1]>20 and x_veggur[i][3]>20:
    
    
        print (hradiy)
    if x_veggur[i][1]<20 and x_veggur[i][3]<20:
        x_veggur[i][0] = random.randrange(0,350)
        x_veggur[i][1] = 400
        x_veggur[i][2] = x_veggur[i][0] 50
        x_veggur[i][3] = 400
        x_veggur_speed -=0.4
    
    
        #print (x_veggur_speed)


    if y>400:
        haetta("GAME OVER")





    pygame.draw.rect(DISPLAYSURF, litur, (x, y, kassi_staerd, kassi_staerd)) #teiknar svarta kassann
    fpsClock.tick(FPS)
    pygame.display.update()
 

Ответ №1:

Сначала вам нужно вычислить y-перемещение игрока:

 move_y = 2
if hoppa==True:
    hoppteljari =1
    if hoppteljari < 20:
        move_y = -2 
    elif hoppteljari>20 and hoppteljari<24:
        move_y = 0
    elif hoppteljari>24:
        move_y = 1
 

Вы должны найти y-расстояние ( dy_platform ) до следующей платформы под вами:

 dy_platform = math.inf
for i in range (0,fjx):
    if x_veggur[i][0] <= x   kassi_staerd and x <= x_veggur[i][2]:
        line_top = x_veggur[i][1]
        player_bottom = (y   kassi_staerd)
        dy = line_top - player_bottom
        if -0.001 <= dy < dy_platform:
            dy_platform = dy 
 

Если расстояние меньше суммы движения платформы вверх и скорости падения игрока, вычислите новую позицию игрока в зависимости от y-положения платформы:

 if dy_platform - move_y   x_veggur_speed <= 0:
    y = y   dy_platform   x_veggur_speed
    hoppa=False
    hoppteljari=0
else:
    y  = move_y 
 

Полный пример:

x_veggur_speed = -0.4 :

x_veggur_speed = -5 :

 import random, time
import pygame, sys
from random import randint
from pygame.locals import *
import math
pygame.init()

#fall sem teiknar veggi lóðrétta og lárétta
def teikna_vegg(x_veggur):
    fjoldi=len(x_veggur)
    for i in range (0,fjoldi):
        pygame.draw.line(DISPLAYSURF, GREEN, (x_veggur[i][0], x_veggur[i][1]),(x_veggur[i][2],x_veggur[i][3]), veggur_breidd)


def haetta(b):      #lokatexti sem kemur þegar forritið er búið
    text = font.render(b, True, WHITE)
    text_rect = text.get_rect()
    text_x = DISPLAYSURF.get_width() / 2 - text_rect.width / 2
    text_y = DISPLAYSURF.get_height() / 2 - text_rect.height / 2
    DISPLAYSURF.blit(text, [text_x, text_y])
    pygame.display.flip()
    #time.sleep(5)
    quit()

# setur upp gluggann
DISPLAYSURF = pygame.display.set_mode((400, 400), 0, 32)    #búa til glugga
pygame.display.set_caption('Lokaverkefni')   #nafn á glugga


FPS = 60 # rammar á sek (hraði)
fpsClock = pygame.time.Clock()

# Litir
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0,255,0)
BLUE = ( 0, 0, 255)
YELLOW = (255,255,0)
litur=BLACK

font = pygame.font.Font(None, 36)   # Leturgerðin sem við notum og stærðin er 36


#upphafshnit kassa


kassi_staerd=10
veggur_breidd=10

#hradi á punkt
hradix=0
hradiy= 0



hoppa = False
hoppteljari = 0

# upphafshnit geimvera á y ás
gx=random.randrange(0,350)
gx = 200
gx2 = gx 50
gy = 360

x = gx
y = 345

x_veggur_speed = -0.4
x_veggur=[[gx,gy,gx2,gy]]

while True: # main game loop
    DISPLAYSURF.fill(RED)
    teikna_vegg(x_veggur)   #Teiknar lárétta veggi
    #hreyfir svarta punktinn
   

    #takkar til að sjtóra kassa
    for event in pygame.event.get(): # event handling loop
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT):
                hradix=-1
            elif (event.key == K_RIGHT):
                hradix=1
            elif (event.key == K_SPACE):
                hoppa=True
            elif event.key == K_ESCAPE:
                pygame.qiuit()
                sys.exit()
        elif event.type == KEYUP:
            if (event.key == K_LEFT ):
                hradix=0
            elif (event.key == K_RIGHT ):
                hradix=0
            elif event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    x  = hradix

    #I think this needs to be changed
    #Athugar hvort að punktur hittir láréttan vegg 
    fjx=len(x_veggur)
    
    move_y = 2
    if hoppa==True:
        hoppteljari =1
        if hoppteljari < 20:
            move_y = -2 
        elif hoppteljari>20 and hoppteljari<24:
            move_y = 0
        elif hoppteljari>24:
            move_y = 1
    
    dy_platform = math.inf
    for i in range (0,fjx):
        if x_veggur[i][0] <= x   kassi_staerd and x <= x_veggur[i][2]:
            line_top = x_veggur[i][1]
            player_bottom = (y   kassi_staerd)
            dy = line_top - player_bottom
            if -0.001 <= dy < dy_platform:
                dy_platform = dy 

    if dy_platform - move_y   x_veggur_speed <= 0:
        y = y   dy_platform   x_veggur_speed
        hoppa=False
        hoppteljari=0
    else:
        y  = move_y 

    for i in range (0,fjx):     # fer í gegnum listan með veggjunum
        x_veggur[i][1]  = x_veggur_speed
        x_veggur[i][3]  = x_veggur_speed  
     
    fjx=len(x_veggur)
    if x_veggur[i][1]>20 and x_veggur[i][3]>20:
        pass
    
        #print (hradiy)
    if x_veggur[i][1]<20 and x_veggur[i][3]<20:
        x_veggur[i][0] = random.randrange(0,350)
        x_veggur[i][1] = 400
        x_veggur[i][2] = x_veggur[i][0] 50
        x_veggur[i][3] = 400
        x_veggur_speed -=0.4
    
    
        #print (x_veggur_speed)

    if y>400:
        haetta("GAME OVER")


    pygame.draw.rect(DISPLAYSURF, litur, (x, y, kassi_staerd, kassi_staerd)) #teiknar svarta kassann
    fpsClock.tick(FPS)
    pygame.display.update()
 

Комментарии:

1. Спасибо за ответы, это мне очень помогло.