微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何构建适当的玩家运动脚本 Pygame

如何解决如何构建适当的玩家运动脚本 Pygame

好的,我是 PyGame 的新手,我正在制作太空入侵者游戏,我目前正在构建运动脚本。

出于某种原因,当我按下右键时,我的角色无限向右移动。

import pygame

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



pygame.display.set_caption('Space Invader')  
icon = pygame.image.load('pepper.png')   
pygame.display.set_icon(icon)            


#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370  
playerY = 480
playerX_Change = 0

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


running = True
while running:

# RGB  STANDS FOR RED,GREEN,BLUE   THE NUMBERS GOES MAX TO  255 FOR EXAMPLE_:

screen.fill((0,30))  # this will display yellow

for event in pygame.event.get():
    if event.type == pygame.QUIT:   #if we click the X the program ends
        running = False

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.1
playerX += playerX_Change
player(playerX,playerY)  

pygame.display.update() 

解决方法

我建议使用 pygame.key.get_pressed() 而不是键盘事件。

键盘事件(参见 pygame.event 模块)仅在键的状态改变时发生一次。 KEYDOWN 事件在每次按下键时发生一次。 KEYUP 每次释放键时出现一次。将键盘事件用于单个操作或逐步移动。

pygame.key.get_pressed() 返回一个包含每个键状态的序列。如果某个键被按下,则该键的状态为 True,否则为 False。使用 pygame.key.get_pressed() 评估按钮的当前状态并获得连续移动:

import pygame

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

pygame.display.set_caption('Space Invader')  
icon = pygame.image.load('pepper.png')   
pygame.display.set_icon(icon)            

#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370  
playerY = 480

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

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:   #if we click the X the program ends
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT] :
        playerX += 0.1
    if keys[pygame.K_LEFT] :
        playerX -= 0.1

    # RGB  STANDS FOR RED,GREEN,BLUE   THE NUMBERS GOES MAX TO  255 FOR EXAMPLE_:
    screen.fill((0,30))  # this will display yellow
    player(playerX,playerY)  
    pygame.display.update() 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。