how do i determine a sprite's position in pygame?

扶醉桌前 提交于 2019-12-23 05:22:09

问题


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



来源:https://stackoverflow.com/questions/15988782/how-do-i-determine-a-sprites-position-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!