Skip to main content
 首页 » 编程设计

python之将移动控件移动到玩家类后,我无法移动 Sprite

2024年09月07日7exmyth

我似乎无法让我的 Sprite 在将它移到一个类后向左或向右移动。我正在使用 pygame。我有一个速度变量并将其添加到我的 x 中以获得我的形状,但它仍然没有移动。任何帮助将非常感激。在我决定将与玩家有关的所有事情都放到一个类(class)之前,运动一直在起作用。

import pygame 
import Constants 
from pygame.locals import * 
pygame.init() 
 
pygame.display.set_caption("Platformer") 
window = pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT)) 
clock = pygame.time.Clock() 
all_sprite_list = pygame.sprite.Group() 
 
class player: 
    def __init__(self,velocity): 
        self.velocity = velocity 
    def location(self,x,y): 
        self.x = x 
        self.y = y  
        self.xVel = 0 
 
    def keys(self): 
        for event in pygame.event.get(): 
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_LEFT: 
                    self.xVel = - self.velocity 
                elif event.key == pygame.K_RIGHT: 
                    self.xVel =  self.velocity 
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 
                    self.xVel = 0 
 
 
 
    def move(self): 
        self.x = + self.xVel 
 
    def draw(self): 
        display = pygame.display.get_surface() 
        pygame.draw.rect(window,(255,255,255),[self.x,self.y,20,40]) 
 
    def do(self): 
        self.keys() 
        self.move() 
        self.draw() 
 
P = player(10) 
P.location(Constants.SCREEN_WIDTH/2,0) 
 
#Map 
def draw_map(): 
    window.fill(Constants.BLUE) 
#sprites 
def draw_player(): 
    player = Player(50,50) 
 
    all_sprite_list.add(player) 
#Game loop  
def game_loop(): 
    GameQuit = False 
    while not GameQuit: 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                GameQuit = True 
 
 
        draw_map() 
        P.do() 
        pygame.display.update() 
        clock.tick(30) 
 
#game initialisation 
game_loop() 
pygame.quit() 
quit() 

`

请您参考如下方法:

问题是 pygame.event.get() 会清除事件队列中的所有事件,因此当您的玩家调用它时,所有事件都已经消失。来自docs

This will get all the messages and remove them from the queue. If a type or sequence of types is given only those messages will be removed from the queue.

您可以通过指定应从事件队列中删除哪些事件来解决此问题,例如

for event in pygame.event.get(QUIT): 
    GameQuit = True 

其他事件仍应在队列中供您的玩家使用