Python 如何移动我的玩家精灵?

Python 如何移动我的玩家精灵?,python,pygame,Python,Pygame,这是我的密码。如何移动我的类Playersprite?我是否将x,y添加到我的def\uuu init\uu?像def\uuu init\uuu(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

这是我的密码。如何移动我的类
Player
sprite?我是否将x,y添加到我的
def\uuu init\uu
?像
def\uuu init\uuu(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()

将两个属性添加到
Player
类以存储播放器的当前速度。在
update
方法中,将速度添加到
x
y
属性中,然后将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)
要向右移动播放机,如果按下“d”键(在本例中),请将
播放机.velocity_x
设置为所需的速度,如果松开该键,请将其设置回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

请不要只是添加随机字母,这样你的帖子就不会大部分是代码。请修复代码和标题。在你的更新功能中,你也可以简单地使用
self.rect.move\u-ip(self.velocity\u x,self.velocity\u-x)
我只对最简单的游戏使用
rect.move\u-ip
rect.x+=speed
。问题是,它只适用于整数(浮点被截断),如果您最终想要使游戏帧速率独立,您必须将速度乘以增量时间,因此必须处理浮点。实际上,我会使用向量来表示位置和速度,但尽量让代码简单一点。因此,这个例子只是朝着正确方向迈出的第一步。这是公平的。令人遗憾的是,pygame提供了向量类,但整个
Sprite
/
/
Rect
系统没有使用它们;因此,您必须手动更改精灵的rect以匹配您的位置向量。如果Sprite类能够自动处理这个问题那就太好了……是的,我实际上已经考虑过为新的pygame版本(应该使用SDL2)提供类似的建议。但是开发人员似乎希望保持所有东西完全向后兼容,我不确定它是否会破坏现有代码,以及它将如何影响性能,等等。