将导弹固定在宇宙飞船上,pygame

时间:2014-04-23 15:14:23

标签: pygame

所以我想要一个导弹贴在我的宇宙飞船上,所以如果宇宙飞船移动,导弹就会随之移动。 我应该制作一个全局变量并将球员位置传递到导弹x&是参数?因为他们分为两个不同的班级

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

1 个答案:

答案 0 :(得分:1)

如果你分享整个代码会更好......你的Missile()课对我来说很模糊,但我不能这样看。

我认为课程是最好的解决方案,但我当然不会在此纠正:)

我建议创建两个类:一般的Ship()类和一个Missile()类(注意:它的拼写"导弹"带有" i"之前" l"!)。

看起来有点像这样:

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

当然还有一些数学要做。例如。当船改变角度时,导弹也应当,然后x / y_offsets不再适合。但我认为,人们从自己的尝试和思考中学到的最多,所以我现在不详细说明;)试着问你是否能让它运转起来。