how do i determine a sprite's position in pyga

2019-06-09 02:31发布

问题:

I'm new to pygame and am making a zombie running game. I am controlling the human with the arrow keys and I would like to have a zombie run toward the player's position when the zombie is first created. I am unsure how to determine the players position to set the zombie in the correct direction. The zombie doesn't have to follow the human, just head in the direction of the players position when the zombie is created.

class Human(pygame.sprite.Sprite):
 def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image=pygame.image.load("human.jpg")
    self.image=self.image.convert()
    self.rect=self.image.get_rect()
    self.x=100
    self.y=430
    self.dx=50
    self.dy=0
 def update(self):
    keys=pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        self.x-=self.dx
    if keys[pygame.K_RIGHT]:
        self.x+=self.dx
    self.rect.center=(self.x,self.y)
class ZombieChase(pygame.sprite.Sprite):
 def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image=pygame.image.load("zombie.jpg")
    self.image=self.image.convert()
    self.rect=self.image.get_rect()
    self.reset()
    self.dx=15
    self.dy=15
    #self.xStart=random.randrange(0,screen.get_width())

 def update(self):
    self.rect.centery+=self.dy

    self.rect.centerx+=self.dx

    if self.rect.top>screen.get_height():
        self.reset()
    if self.rect.right>screen.get_width():
        self.reset()
    if self.rect.left<0:
        self.reset()


 def reset(self):
    self.rect.top=0
    speed=random.randrange(20,36)
    xStart=random.randrange(0,screen.get_width())
    yStart=0
    #humanx, humany  !!!!!!this is where i don't know what to put!!!!!
    try:
        self.dx=(humanx-xStart)/speed
    except ZeroDivisionError:
        self.dx=0
    try:
        self.dy=(humany-yStart)/speed
    except ZeroDivisionError:
        self.dy=1

    self.rect.centerx=xStart

Sorry if the tabbing isn't right.

回答1:

If you subclass pygame.sprite.Sprite the location is zombie.rect . For coords, zombie.rect.center or zombie.rect.topleft