让雪碧面对老鼠?

2024-04-20 09:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着让我的精灵移动并面对我的老鼠。然而,当我尝试这段代码时,精灵只是旋转并分裂成不同的部分,并开始移出屏幕,而我没有移动精灵

我也尝试过使用as_polar()函数,但是精灵每次只旋转几度 在它停止之前

class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
    self.groups = game.all_sprites
    pg.sprite.Sprite.__init__(self, self.groups)
    self.game = game
    self.image = game.player_img
    self.rect = self.image.get_rect()
    self.vel = vec(0, 0)
    self.pos = vec(x, y) * TILESIZE

def get_keys(self):
    self.vel = vec(0, 0)
    keys = pg.key.get_pressed()
    if keys[pg.K_LEFT] or keys[pg.K_a]:
        self.vel.x = -PLAYER_SPEED
    if keys[pg.K_RIGHT] or keys[pg.K_d]:
        self.vel.x = PLAYER_SPEED
    if keys[pg.K_UP] or keys[pg.K_w]:
        self.vel.y = -PLAYER_SPEED
    if keys[pg.K_DOWN] or keys[pg.K_s]:
        self.vel.y = PLAYER_SPEED
    if self.vel.x != 0 and self.vel.y != 0:
        self.vel *= 0.7071

def collide_with_walls(self, dir):
    if dir == 'x':
        hits = pg.sprite.spritecollide(self, self.game.walls, False)
        if hits:
            if self.vel.x > 0:
                self.pos.x = hits[0].rect.left - self.rect.width
            if self.vel.x < 0:
                self.pos.x = hits[0].rect.right
            self.vel.x = 0
            self.rect.x = self.pos.x
    if dir == 'y':
        hits = pg.sprite.spritecollide(self, self.game.walls, False)
        if hits:
            if self.vel.y > 0:
                self.pos.y = hits[0].rect.top - self.rect.height
            if self.vel.y < 0:
                self.pos.y = hits[0].rect.bottom
            self.vel.y = 0
            self.rect.y = self.pos.y

def rotate(self):
    mouseX, mouseY = pg.mouse.get_pos()
    angle = math.atan2(mouseX - self.pos.x, mouseY - self.pos.y)
    self.image = pg.transform.rotate(self.image, -angle)
    self.rect = self.image.get_rect(center=self.rect.center)


def update(self):
    self.rotate()
    self.get_keys()
    self.pos += self.vel * self.game.dt
    self.rect.x = self.pos.x
    self.collide_with_walls('x')
    self.rect.y = self.pos.y
    self.collide_with_walls('y')