我试图通过按箭头键向左或向右移动精灵(称为Player)。向右或向左移动将通过更改子画面矩形的中心进行。如您所见,我试图从精灵的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()
答案 0 :(得分:1)
您从未更改精灵player
的位置。
您希望它如何移动?
您要做的只是更改局部变量playerx
的值,但您从未将这一更改推回到sprite对象中。
首先在下面添加中间行:
playerx += x_change
player.rect.center = (playerx, playery)
all_sprites.update()
看看这会如何改变事情?你可以从那里拿走吗?
答案 1 :(得分:0)
还需要用背景颜色或图像填充屏幕,以使屏幕更新为移动的精灵的当前位置。以下命令将添加到游戏循环的绘制/渲染部分的顶部:
screen.fill(black)