0

So i am trying to get my sprite move and face my mouse. However when I try this code the sprite just rotates and splits into different parts and start moving out of the screen without I am moving the sprite.

I have also tried with the as_polar() function but then the sprite just rotates a few degrees each way before it stops....

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')
  • First read: [How do I rotate an image around its center using PyGame?](https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame/54714144#54714144). Then read: [How to rotate an image(player) to the mouse direction?](https://stackoverflow.com/questions/58603835/how-to-rotate-an-imageplayer-to-the-mouse-direction/58604116#58604116). Finally read [move towards the mouse cursor and point towards it](https://stackoverflow.com/questions/65442583/how-do-i-get-this-spaceship-to-move-towards-the-mouse-cursor-and-point-towards-i/65449778#65449778) – Rabbid76 Jul 26 '21 at 14:45

0 Answers0