如何移动我的玩家精灵?

时间:2017-07-03 22:39:04

标签: python pygame

这是我的代码。如何移动我的班级Player精灵?我会在def __init__添加x,y吗?像def __init__(self, x, y)?谢谢你的回答,

import pygame as pg
WIDTH = 800
HEIGHT = 600

CLOCK = pg.time.Clock()
FPS = 60

GREEN = (0, 255, 0)
LIGHTBLUE = (20, 130, 230)
BGCOLOR = LIGHTBLUE

class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT / 2))
        self.x = x
        self.y = y

player = Player()

pg.init()

screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('The Moon Smiles Back')

running = True
while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False

    all_sprites = pg.sprite.Group()
    all_sprites.add(player)
    all_sprites.update()
    screen.fill(BGCOLOR)
    all_sprites.draw(screen)
    pg.display.flip()

    CLOCK.tick(FPS)

pg.quit()

1 个答案:

答案 0 :(得分:0)

Player类添加两个属性以存储播放器的当前速度。在update方法中,将速度添加到xy属性,然后将rect设置为新位置。

class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.x = x
        self.y = y
        self.velocity_x = 0
        self.velocity_y = 0

    def update(self):
        self.x += self.velocity_x
        self.y += self.velocity_y
        self.rect.center = (self.x, self.y)

要将播放器向右移动,请将player.velocity_x设置为所需的速度,如果' d'按下键(在此示例中),如果释放键,则返回0。对其他方向也这样做。

if event.type == pg.KEYDOWN:
    if event.key == pg.K_ESCAPE:
        running = False
    elif event.key == pg.K_d:
        player.velocity_x = 3
elif event.type == pg.KEYUP:
    if event.key == pg.K_d:
        player.velocity_x = 0
相关问题