我试图在pygame中制作精灵投掷手榴弹。我想要的是让它前进一点,然后停下来。我的问题是让手榴弹顺利前进。以下代码的作用是让它立即移动到引人注目的位置,而不是平稳移动。
[手榴弹班]
#Grenade Class
class Explosive(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self)
self.pos = location
self.image = Nade
self.rect = self.image.get_rect()
self.rect.right = self.image.get_rect().right
self.rect.left = self.image.get_rect().left
self.rect.top = self.image.get_rect().top
self.rect.bottom = self.image.get_rect().bottom
self.rect.center = location
def move(self):
if Player.direction == 0:
self.rect.centery = self.rect.centery - 5
if Player.direction == 180:
self.rect.centery = self.rect.centery + 5
if Player.direction == 90:
self.rect.centerx = self.rect.centerx + 5
if Player.direction == 270:
self.rect.centerx = self.rect.centerx - 5
[投掷手榴弹(在主循环中)]
if event.key == pygame.K_e and grenadeNum > 0:
Grenade = Explosive([Player.rect.centerx, Player.rect.centery])
for i in range(1, 10)
Grenade.move()
答案 0 :(得分:1)
虽然您确实需要更新显示屏,但还有第二个问题。现在,你并没有告诉它等待它,所以它将毫不拖延地完成所有十个动作。这将是一个突然的,所以你可能想要导入时间并在那里的某处添加time.sleep()。因为在一个自包含的“for”循环中移动手榴弹,如果你还有其他任何事情,这将停止。如果你有一个while循环来管理一切,在手榴弹上调用一个“更新”功能,他们将有计数器来知道他们是否应该在这一轮中移动。如果其他精灵需要做某事,你也可以调用他们的方法。最后,为了加速程序,你只能更新精灵移动部分的屏幕。当你把它们放在一起时,它就是这样的:
import time
grenades = pygame.sprite.RenderUpdates() #initializes a pygame group for sprites
class Explosive(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self)
self.pos = location
self.image = Nade
self.rect = self.image.get_rect()
self.rect.right = self.image.get_rect().right
self.rect.left = self.image.get_rect().left
self.rect.top = self.image.get_rect().top
self.rect.bottom = self.image.get_rect().bottom
self.rect.center = location
self.move_counter = 10 #adds a counter for how many rounds left of moving the grenade has
def update(self):
if self.move_counter > 0: #checks that self still has turns left to move
<insert screen variable name>.fill(<insert background color>,self.rect) #erases self in old location
if Player.direction == 0:
self.rect.centery = self.rect.centery - 5
if Player.direction == 180:
self.rect.centery = self.rect.centery + 5
if Player.direction == 90:
self.rect.centerx = self.rect.centerx + 5
if Player.direction == 270:
self.rect.centerx = self.rect.centerx - 5
pygame.display.update(self.draw((screen))) #draws self in new location
self.move_counter -= 1 #subtracts one from the counter to mark that another turn of moving has passed by
while True:
grenades.update()
#anything else you want to do in real time here
time.sleep(0.1)
答案 1 :(得分:0)
你需要在每次移动后重新绘制屏幕,我认为代码是:
pygame.display.update()
所以你的for循环应该是这样的:
for i in range(1, 10)
Grenade.move()
pygame.display.update()
这可能效率不高,所以一定要注意更有效的方法,例如,如果手榴弹是场景中唯一的移动物体,那么你将只想重绘它。