Question

So I want a missle to stick to my spaceship,so if the spaceship moves the missle will move with it. Should I make a global variable and pass players position into the missle x & y parameters? cause they are in two different classes

Missle1    = Missle(screen,(x_pos,y_pos),playerShip)

class PlayerShip(pygame.sprite.Sprite):
    def __init__(self, screen, (x, y)):
        pygame.sprite.Sprite.__init__(self)
        self.screen = screen
        self.image = pygame.image.load("player.png")
        self.image = self.image.convert()
        tranColor = self.image.get_at((1, 1))
        self.image.set_colorkey(tranColor)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.health = 100


    def update(self):
        x_pos =self.rect.centerx 
        y_pos =self.rect.centery
Was it helpful?

Solution

It would be better if you'd share the whole code... Your Missile() class is pretty obscure to me but I can't have a look at it like this.

I deem classes to be the best solution here, but I surely wouldn't mind to be corrected in this :)

I suggest to create two classes: a general Ship() class and a Missile() class (note: It's spelled "missile" with an "i" before the "l"!).

It could look somewhat like this:

class Ship(pygame.sprite.Sprite):
    def __init__(self, ...):
         #your code here
         self.missiles = [Missiles(x, y, x_offset, y_offset)]

    def update(self):
        #update ship's x and y coordinates
        for missile in self.missiles:
            missile.update(self.rect.center)
        #Did you notice? We call "update" for each of the instances of Missile() in our
        #ship's "self.missiles" list and pass it our self.rect.center as argument

class Missile(pygame.sprite.Sprite):
    def __init__(self, x, y, x_offset, y_offset):
        self.x = x
        self.y = y
        self.x_offset = x_offset #how much offset to the ship's x?
        self.y_offset = y_offset

    def update(self, (x, y)):
        self.x = x + self.x_offset
        self.y = y + self.y_offset

of course there's some math to do. E.g. when the ship changes its angle, then the missiles also should and then the x/y_offsets don't fit anymore. But I think, people learn most from trying and thinking on their own, so I don't go into detail with this now ;) Try and ask if you can't get it running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top