How to get the current coordinates of a sprite in pygame?

Viewed 463

I am trying to make a simple game where the player has to either dodge enemies or shoot at them. So far the player and enemies part seems good, but I am stuck in the missile thing. I am trying to figure out how to spawn a missile right next to the player when the left mouse button is pressed. So I am looking for a way to get the current coordinates of the player, add one to the right of those coordinates and that what would be the coordinates of the missile in case the player pressed the left button.

class Player(pg.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pg.image.load("Player.png").convert()
        self.surf = pg.transform.smoothscale(self.surf, (75, 75))
        self.surf.set_colorkey((255, 255, 255), RLEACCEL)
        self.rect = self.surf.get_rect()
    def move(self, pressed_keys):
        if pressed_keys[K_UP]:
            self.rect.move_ip(0, -10)
        if pressed_keys[K_DOWN]:
            self.rect.move_ip(0, 10)
        if pressed_keys[K_LEFT]:
            self.rect.move_ip(-10, 0)
        if pressed_keys[K_RIGHT]:
            self.rect.move_ip(10, 0)
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= SCREEN_HEIGHT:
            self.rect.bottom = SCREEN_HEIGHT

class Missile(pg.sprite.Sprite):
    def __init__(self):
        super(Missile, self).__init__()
        self.surf = pg.image.load("Missile.png").convert()
        self.surf = pg.transform.smoothscale(self.surf, (20, 20))
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(center=)
    def launch(self):
        self.rect.move_ip(5, 0)
        if self.rect.left < 0:
            self.kill()
1 Answers

The coordinates are stored in the rect attribute. The rect attribute is a pygame.Rect object and specifies the bounding rectangle of the Sprite. It offers numerous virtual attributes for position and size. For example, the top left of the Sprite is self.rect.topleft or (self.rect.x, self.rect.y).

I suggest to pass the initial coordinates to the Missile object:

class Missile(pg.sprite.Sprite):
    def __init__(self, pos):
        super(Missile, self).__init__()
        self.surf = pg.image.load("Missile.png").convert()
        self.surf = pg.transform.smoothscale(self.surf, (20, 20))
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(center = pos)

Get the current coordinates from the player when a new Missile object is created. e.g:

missile_pos = player.rect.center
new_missile = Missile(missile_pos)
Related