简体   繁体   English

如何让玩家角色移动?

[英]How do I get the player character to move?

I was starting to improve my code when I encountered a roadblock.当我遇到障碍时,我开始改进我的代码。 My player character can jump but cannot move left and right.Program runs as if there are no syntax errors.我的玩家角色可以跳跃但不能左右移动。程序运行就像没有语法错误一样。 The main aim is trying to get the character to move left and right主要目的是试图让角色左右移动

here is the player class where its attributes and functions are defined这里是播放器 class 定义了它的属性和功能

class player:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.width = 64
        self.height = 64
        self.standing = True
        self.left = False
        self.right = True
        self.vel = 15
        self.jumping = False
        self.jumpCount = 10
        self.k = pygame.key.get_pressed()
    def move(self,x,y):
        if not self.standing:
            if self.k[pygame.K_LEFT] and self.x  > 0 - 150:
                self.left = True
                self.right = False            
                self.x -= self.vel
            elif self.k[pygame.K_RIGHT] and self.x  < 500 - 150 :
                self.right = True
                self.left = False
               self.x += self.vel
        else:
            self.standing = True

Main loop主循环

run = True
wizard = player(25,320)
while run:#main game loop
    pygame.time.delay(15)
    for event in pygame.event.get():#loops through a list of keyboard or mouse events
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                wizard.jumping = True    
    wizard.move(wizard.x,wizard.y)
    win.blit(bg,(0,0))
    wizard.jump(wizard.y)
    wizard.draw(win) 
    pygame.display.update()
pygame.quit()

Ok, some of the code seems a bit mixed-up.好的,有些代码似乎有点混乱。 I think it would be better if your player class just handled being a wizard (which is a big enough task on its own), and your main event-loop should take care the user-input.我认为如果您的player class 只是处理作为向导(这本身就是一项足够大的任务),并且您的主事件循环应该注意用户输入,那会更好。

The main loop is using the pygame.KEYDOWN event.主循环使用pygame.KEYDOWN事件。 This is fine if you want that key-down, key-up "typing" sort of movement.如果您想要那种按下键、向上键“打字”的运动,这很好。 But a more natural way is to simply check pygame.key.get_pressed() which returns the state of all buttons.但更自然的方法是简单地检查pygame.key.get_pressed() ,它返回所有按钮的 state。 Since your player already maintains a velocity, use the key-states to adjust the velocity.由于您的播放器已经保持了速度,因此请使用键状态来调整速度。

FPS=20
clock = pygame.time.Clock()   # clock to limit the FPS
while run: #main game loop
    #pygame.time.delay(15)   # <-- No need to delay here, see FPS limit below
    for event in pygame.event.get():  #loops through event list
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                wizard.goJump()

    # Handle keys pressed
    if ( keys[pygame.K_LEFT] ):
        wizard.goLeft()
    elif ( keys[pygame.K_RIGHT] ):
        wizard.goRight()

    # Update the player's position
    #wizard.move(wizard.x,wizard.y)
    wizard.update()

    # redraw the screen
    win.blit( bg, (0, 0) )
    wizard.draw( win ) 
    pygame.display.update()

    # Update the window, but at a useful FPS
    clock.tick_busy_loop( FPS )

pygame.quit() 

So this means a few changes to the player .所以这意味着对player进行一些更改。 I've tried to keep all the "player handling" functions inside the player, while moving all the user-input handling code outside of the class.我试图将所有“播放器处理”功能保留在播放器内部,同时将所有用户输入处理代码移到 class 之外。

class player:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.width = 64
        self.height = 64
        #self.standing = True          <-- Standing is "not self.jumping"
        #self.left = False
        #self.right = True
        self.vel = 15                 # current player speed
        self.max_vel = 20             # Limit the player speed extremes
        self.mix_vel = -20
        self.jumping = False
        self.jumpCount = 10
        # self.k = pygame.key.get_pressed()  <-- Don't handle events inside the player

    def goLeft( self ):
        """ Handle the user-input to move left """      
        self.vel -= 1
        if ( self.vel <= self.min_vel ):
            self.vel = self.min_vel

    def goRight( self ):
        """ Handle the user-input to move right """
        self.vel += 1
        if ( self.vel >= self.max_vel ):
            self.vel = self.max_vel

    def goJump( self ):
        """ Handle the user-input to jump """
        if ( self.jumping == False ):
            self.jumping = True
            print( "TODO: Handle Jumping" )
        else:
            print( "TODO: Already Jumping" )

    def update( self ):
        # Move the character left/right
        self.x += self.vel   # (+) velocity is right, (-) is left
        # handle the progress of the jump
        if ( self.jumping == True ):
            print( "TODO: jump wizard - GO!" )

The jumping is not implemented.跳跃没有实现。 One way to do this is instead of simply recording self.jumping as boolean, perhaps store the milliseconds-time the jump started instead.一种方法不是简单地将self.jumping记录为 boolean,而是存储跳转开始的毫秒时间。 Then during the player.update() , use the real-time difference to move the player through their (parabolic?) path up & back down.然后在player.update()期间,使用实时差异来移动玩家通过他们的(抛物线?)路径上下移动。 Once player.jumptime is reset back to zero, they user can make the wizard jump again.一旦player.jumptime重置为零,他们的用户可以让向导再次跳转。

The problem is self.k of your player class is just the state of the keys at the moment of the creation of the player.问题是您的播放器self.k的 self.k 只是创建播放器时键的 state 。 Try to put self.k=pygame.key.get_pressed() in the move function of the player.尝试将self.k=pygame.key.get_pressed()放在玩家的移动 function 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM