Обнаружение столкновения: посадка мяча на платформу - PullRequest
0 голосов
/ 23 января 2020

Я пытаюсь сделать игру и на платформах, случайно генерирующих перемещение в верхнюю часть экрана. Мяч приземляется на генерируемые платформы.

for i in range (12):
    platforms.append([random.randint(1,w), random.randint(1,h), random.randint(speed,-1)])

while True:  
    screen.fill(black)

    # Platforms
    for  i in range (len(platforms)):
        pygame.draw.rect (screen,white,(platforms[i][0],platforms[i][1],rectW,rectH))
        platforms[i][1] = platforms [i][1] + platforms [i][2]
        if (platforms [i][1] < 0):
            platforms [i][1] = h-death
            platforms [i][0] = random.randint(1,w)
    # Collision Detection
    print (x1,y1,platforms[i][1])
    for i in range (len(platforms)):
        if x1 >= platforms[i][0] and x1 <= platforms[i][0] + rectW:
            print ('hello')
            if y1 == platforms[i][0]:
                print ("HIT")

Что мне нужно изменить, чтобы заставить y1 двигаться вверх по платформе или сделать печать "HIT"

1 Ответ

0 голосов
/ 23 января 2020

РЕДАКТИРОВАТЬ: Коротко: вы должны использовать <= вместо == и [1] вместо [0]

if y1 <= platforms[i][1]: 
   print ("HIT")
   y1 = platforms[i][1] # move up with platform

Сначала вы должны использовать pygame.Rect() чтобы сохранить положение и размер. Он имеет свойство x y width, height, но также полезно bottom, top, center и т. Д. c.

Также имеется метод для проверки столкновения между двумя Rect()

player_rect.colliderect(platform_rect)

Когда вы получаете столкновение между игроком и платформой, вы должны изменить bottom игрока, используя top * платформы 1027 *

    if player_rect.colliderect(platform_rect):
        player_rect.bottom = platform_rect.top

и он будет перемещать игрока с платформой.


Минимальный рабочий код: красная платформа движется вверх и автоматически игрок поднимается тоже.

import pygame

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25 # for more than 220 it has no time to update screen

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# --- functions --- (lower_case_names)

# --- main ---

pygame.init()

screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
screen_rect = screen.get_rect()

player_rect = pygame.Rect(0,0,50,50)
player_color = (0,255,0)
player_rect.centerx = screen_rect.centerx
player_rect.bottom = screen_rect.bottom-25

platform_rect = pygame.Rect(0,0,200,25)
platform_color = (255,0,0)
platform_rect.centerx = screen_rect.centerx
platform_rect.bottom = screen_rect.bottom

# --- mainloop ---

clock = pygame.time.Clock()

running = True
while running:

    # --- events ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False


    # --- changes/moves/updates ---

    platform_rect.y -= 1

    if player_rect.colliderect(platform_rect):
        player_rect.bottom = platform_rect.top

    # --- draws ---

    screen.fill(BLACK)

    pygame.draw.rect(screen, player_color, player_rect)    
    pygame.draw.rect(screen, platform_color, platform_rect)    

    pygame.display.flip()

    # --- FPS ---

    ms = clock.tick(FPS)

# --- end ---

pygame.quit()

РЕДАКТИРОВАТЬ: Пример с движением платформы вниз. Он использует player_gravity, чтобы удерживать игрока на платформе, когда платформа опускается.

Если player_gravity совпадает с plaftorm_speed, то игрок остается на платформе - но он player_gravity меньше plaftorm_speed, тогда игрок падает медленнее, чем платформа (как с парашютом)

import pygame

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 25 # for more than 220 it has no time to update screen

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# --- functions --- (lower_case_names)

# --- main ---

pygame.init()

screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
screen_rect = screen.get_rect()

player_rect = pygame.Rect(0,0,50,50)
player_color = (0,255,0)
player_rect.centerx = screen_rect.centerx
player_rect.bottom = screen_rect.bottom-25
player_gravity = 3 # try 5

platform_rect = pygame.Rect(0,0,200,25)
platform_color = (255,0,0)
platform_rect.centerx = screen_rect.centerx
platform_rect.bottom = screen_rect.bottom
platform_direction = 'top'
platform_speed = 5

# --- mainloop ---

clock = pygame.time.Clock()

running = True
while running:

    # --- events ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False


    # --- changes/moves/updates ---

    if platform_direction == 'top':
        platform_rect.y -= platform_speed
        if platform_rect.top <= 100:
            platform_direction = 'bottom'
    else:
        platform_rect.y += platform_speed
        if platform_rect.bottom >= 600:
            platform_direction = 'top'

    player_rect.y += player_gravity 

    if player_rect.colliderect(platform_rect):
        player_rect.bottom = platform_rect.top

    # --- draws ---

    screen.fill(BLACK)

    pygame.draw.rect(screen, player_color, player_rect)    
    pygame.draw.rect(screen, platform_color, platform_rect)    

    pygame.display.flip()

    # --- FPS ---

    ms = clock.tick(FPS)

# --- end ---

pygame.quit()
...