我用Python编写了这段代码,当我按下按钮时,它应该相应地向右和向左移动,但它不是[重复]

mwkjh3gx  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(83)
    • 此问题在此处已有答案**:

How can I make a sprite move when key is held down(6个答案)
11小时前关门了。
这里我已经写了playerX_change的代码(它是第一次定义为0的值),当按下任何键(如左或右)时,它应该通过改变x的值来响应,但它没有
我试图纠正索引,也试图为它创建新的变量,请尝试其他东西,并提出建议的变化
这是密码

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("It's a game -_-")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

running: bool = True

playerimg = pygame.image.load('spaceship3.png')
playerX = 370
playerY = 480

def player(x, y):
    screen.blit(playerimg, (x, y))

while running:
    screen.fill((22, 11, 222))
    playerX_change = 0
    player(playerX, playerY)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # it shows basically that every key pressed inside the window gets stored in pygame.event
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            playerX_change = -0.1
        if event.key == pygame.K_RIGHT:
            playerX_change =0.1
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            playerX_change = 0
sigwle7e

sigwle7e1#

欢迎来到社区,您尝试做的是在按左/右键时向左或向右移动播放器,但是,您没有通过PlayerX_change更改PlayerX变量。因此,这不会移动播放器,请尝试将PlayerX_change = 0替换为PlayerX += PlayerX_change,以便更新播放器的X位置,并且它只会在向上键时停止。

相关问题