我无法使用我的代码上下移动

时间:2016-09-28 23:16:47

标签: python pygame

这是我用来为游戏使用矩形移动的代码。但每次按下上下键,它都会左右移动。如果您可以在答案中粘贴正确的版本。谢谢!!!!

p.s#是评论

#to start pygame
import pygame

pygame.init()

#game window
gameWindow = pygame.display.set_mode((1000, 600))
pygame.display.set_caption("SimpleShooter")

#moving character
class PlayerActive():
    def __init__(self):

        self.image = pygame.Surface((50, 50))
        self.image.fill((0, 0, 255))
        self.rect = self.image.get_rect()

        self.rect.x = 50
        self.rect.y = 50

        self.speed = 1

    def move(self, xdir, ydir):
        self.rect.x += xdir*self.speed
        self.rect.x += ydir*self.speed

player = PlayerActive()

#starting and ending the game
gameActive = True
while gameActive:
    for event in pygame.event.get():
        #print event (optional)
        if event.type == pygame.QUIT:
            gameActive = False

    #moving character
    activekey = pygame.key.get_pressed()

    if activekey[pygame.K_RIGHT]:
        player.move(1, 0)
    if activekey[pygame.K_LEFT]:
        player.move(-1, 0)
    if activekey[pygame.K_UP]:
        player.move(0, -1)
    if activekey[pygame.K_DOWN]:
        player.move(0, 1)

    #change the main screen
    gameWindow.fill((255, 255, 255))
    #place moving character
    gameWindow.blit(player.image, player.rect)
    #how to draw rectangles
    pygame.draw.rect(gameWindow, (0, 0, 0), (50, 195, 50, 50), 5)
    #use to show shapes on gameWindow
    pygame.display.update()

#quit game
pygame.quit()
quit()

1 个答案:

答案 0 :(得分:1)

以下内容:

def move(self, xdir, ydir):
    self.rect.x += xdir*self.speed
    self.rect.x += ydir*self.speed

应改为:

def move(self, xdir, ydir):
    self.rect.x += xdir*self.speed
    self.rect.y += ydir*self.speed

无论更改是x还是xdir,您总是递增ydirrect.y的更改ydirrect.x的{​​{1}}更改。