我如何确定精灵在pygame中的位置? [英] how do i determine a sprite's position in pygame?
问题描述
我是pygame的新手,正在制作一部僵尸跑步游戏.我正在使用箭头键控制人类,我希望在首次创建僵尸时让僵尸向玩家的位置奔跑.我不确定如何确定玩家的位置以将僵尸设置在正确的方向上.僵尸不必跟随人类,只要在创建僵尸时朝玩家位置的方向走即可.
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.
推荐答案
如果您将pygame.sprite.Sprite
子类化,则位置为zombie.rect
.对于坐标,zombie.rect.center
或zombie.rect.topleft
If you subclass pygame.sprite.Sprite
the location is zombie.rect
. For coords, zombie.rect.center
or zombie.rect.topleft
这篇关于我如何确定精灵在pygame中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!