Pygame 中的精灵在无限循环中上下移动

问题描述 投票:0回答:1

我对 pygame 了解不多,所以我只是在 pygame.org 上复制了一个教程,精灵只是循环地上下旋转。

import sys, pygame
pygame.init()

size = width, height = 500, 500
speed = [2, 2]
blue = 85, 118, 250

screen = pygame.display.set_mode(size)

bird = pygame.image.load("bird-sprite.png")
birdrect = bird.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    birdrect = birdrect.move(speed)
    if birdrect.left < 0 or birdrect.right > width:
        speed[0] = -speed[0]
    if birdrect.top < 0 or birdrect.bottom > height:
        speed[1] = -speed[1]
        
    screen.fill(blue)
    screen.blit(bird, birdrect)
    pygame.display.flip()

我试图为精灵创建运动,但精灵只是在整个窗口周围移动而没有在无限循环中停止。

我使用了 pygame.org,因为我找不到关于运动的确切教程,所以是的。

我不太了解 Python,所以我不知道我做错了什么。

python pygame 2d-games
1个回答
0
投票

嗯,它完全按照代码告诉它做的 - 每帧将鸟移动 2 个像素(

speed
变量):

# This line of code moves bird sprite every frame by 2 pixels
birdrect = birdrect.move(speed)

# This lines of code checks if bird sprite is outside of the screen
# If it is - then speed inverts, so bird starts moving in the opposite way
if birdrect.left < 0 or birdrect.right > width:
        speed[0] = -speed[0]
    if birdrect.top < 0 or birdrect.bottom > height:
        speed[1] = -speed[1]

如果你想实现移动,你真的应该阅读一堆关于 pygame 的教程。

这是我简单的移动实现(鸟类使用方向键移动):

import sys, pygame
pygame.init()

size = width, height = 500, 500
speed = [0.1, 0.1]
blue = 85, 118, 250

screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

bird = pygame.image.load("bird-sprite.png")
birdrect = bird.get_rect()

# Coordinates of bird
bird_x, bird_y = birdrect.x, birdrect.y

# Speed of bird in px/second
speed = 200

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    # Calculate how many milliseconds passed since previous frames
    # This is necessary for smooth movement
    time_passed = clock.tick(60) / 1000

    # Get pressed keys state
    pressed_keys = pygame.key.get_pressed()

    # If LEFT is pressed - subtract speed*time_passed from bird`s X coordinate
    # this means that when you press LEFT for 1 second - bird will move 200 pixels left
    # Do same calculations for every key
    if pressed_keys[pygame.K_LEFT]:
        bird_x -= speed * time_passed

    if pressed_keys[pygame.K_RIGHT]:
        bird_x += speed * time_passed

    if pressed_keys[pygame.K_DOWN]:
        bird_y += speed * time_passed

    if pressed_keys[pygame.K_UP]:
        bird_y -= speed * time_passed

    # Apply changes to bird's rect
    birdrect.x = int(bird_x)
    birdrect.y = int(bird_y)

    # Draw everyting
    screen.fill(blue)
    screen.blit(bird, birdrect)

    # Update display
    pygame.display.flip()
© www.soinside.com 2019 - 2024. All rights reserved.