sprite不会在pygame中向左或向右移动

2024-09-29 20:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过按箭头键将精灵(称为玩家)向左或向右移动。这个长方形的中心或者说是由右边的移动所造成的。正如你可能看到的,我试图从精灵的x坐标中加上/减去8,以便将其向右或向左移动。但是,当我按下箭头键时,精灵不会移动。我该怎么解决这个问题?在

import pygame
import random
import time
import pygame as pg


# set the width and height of the window
width = 800
height = 370
groundThickness = 30
pheight = 50
pwidth = 50
playerx = 0+pwidth
playery = height-groundThickness-pheight/2
fps = 30
# define colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (5, 35, 231)
# initialize pygame 
pygame.init()

# initialize pygame sounds
pygame.mixer.init()
# create window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("my game")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.image = pygame.Surface((pwidth, pheight))
            self.image.fill(red)
            self.rect = self.image.get_rect()
            self.rect.center = (playerx, playery)

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# Game loop
running = True
x_change = 0
while running:
    # keep loop running at the right speed
    clock.tick(fps)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("left")
                x_change = -8
            elif event.key == pygame.K_RIGHT:
                print("right")
                x_change = 8
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0
        print(x_change)
        playerx += x_change
        all_sprites.update()



    #ground
    pygame.draw.rect(screen, (0,255,0), ((0, height-groundThickness), (width, groundThickness)))



    # Update
    all_sprites.update()



    # Draw / render
    all_sprites.draw(screen)
    pygame.display.update()
    # AFTER drawing everything, flip the display
    pygame.display.flip()

pygame.quit()

Tags: therectimportselfeventifinitdisplay
2条回答

用你的背景色或图像填充屏幕也需要保持你的屏幕随着移动精灵的当前位置而更新。以下命令将添加到游戏循环的“绘制/渲染”部分的顶部:

screen.fill(black)

你从未改变精灵的位置player。 你希望它怎么移动? 您所做的只是更改局部变量playerx的值,但您从未将该更改推回到sprite对象中。在

首先在下面添加中间线:

    playerx += x_change
    player.rect.center = (playerx, playery)
    all_sprites.update()

你看这会改变什么吗?你能从那里拿走吗?在

相关问题 更多 >

    热门问题