我对OOP和pygame还比较陌生,所以这些可能是一些愚蠢而基本的问题——但我已经坚持了好几天了,所以任何事情都会有所帮助
我正在Gun.shoot()中创建一个名为position3的变量,我希望在调用Bullet.reposition时将此变量移到Bullet.reposition()。然后我希望position3变量移到Bullet.update()函数,该函数由代码中其他地方的不同进程调用。在整个过程中,position3变量不应改变,而应保持不变。我已经设法使position3变量从Gun.shoot()移到Bullet.reposition(),但是现在无法将它移到Bullet.update()中。救命啊
class Bullet(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((5,5))
self.image.fill(red)
self.rect = self.image.get_rect()
# self.rect.center = (200,200)
self.positionofm = (23,0)
self.pos = vec(300,300)
self.centerlocation = vec(0,0)
self.position3 = vec(0,0)
def update(self):
self.position3 = reposition.position3
print("update",self.position3)
# self.rect.center = self.position3
self.centerlocation = random.randint(200,400),random.randint(200,400)
self.rect.center =(self.centerlocation)
def reposition(self,position3):
print("repositioning")
self.centerlocation = random.randint(200,400),random.randint(200,400)
self.rect.move(position3)
print("regular",position3)
self.position3 = position3
print("First update",self.position3)
class Gun(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((30,5), pg.SRCALPHA)
self.image.fill(black)
self.rect = self.image.get_rect()
self.original_image = self.image
self.rect.center = (WIDTH/2 , HEIGHT/2)
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.offset = vec(20, 0)
self.angle=0
self.position2=vec(0,0)
# self.bullet = Bullet()
def shoot(self):
self.BulletEndPos=vec(0,0)
self.BulletEndPos=vec(pg.mouse.get_pos())
# print(self.BulletEndPos,"akshgdjasgdas")
position2x=self.position2[0]
position2y=self.position2[1]
position3=vec(0,0)
position3=(math.floor(position2x)),(math.floor(position2y))
Bullet.reposition(self, position3)
好吧,你的代码片段已经有了你所需要的一切,你只需要删除这行
假设重新定位不是对象,也不会保留属性
position3的值已经为重定位方法上的对象更新,并写入Bullet object属性。另一种方法是重写update(),有点像这样:
这使您可以根据需要在代码中的其他位置传递位置3,同时保留逻辑
现在只想澄清几件事:
记住,在你的最后一行方法拍摄你什么也没做,有没有子弹创建重新定位和更新。所以你需要把枪的等级改成:
OOP有时可能会让人困惑,尤其是在开始的时候,因此您可以在线尝试其他资源(例如https://www.tutorialspoint.com/python3/python_classes_objects.htm)
相关问题 更多 >
编程相关推荐