是否有可能在我点击的位置放置一个Sprite?
class sprite_to_place(pygame.sprite.Sprite):
def __init__(self, x_start_position , y_start_position ):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("a_picture.png")
self.rect = self.image.get_rect()
self.rect.x = x_start_position # x where I clicked
self.rect.y = y_start_position # y where I clicked
当我初始化sprite_to_place时,我会使用pygame.mouse.get_pos()
。
在主循环中,我将它放在:
if event.type == pygame.MOUSEBUTTONDOWN:
sprite_to_place_group.draw(gameDisplay)
但是,如果我想用def update()
更改其位置,我怎样才能获得精灵的位置? (我使用allsprites_group.update()
)
def update(self, startpos=(x_start_position, y_start_position)): # how can I tell the function where the sprite is on the map?
self.pos = [startpos[0], startpos[1]]
self.rect.x = round(self.pos[0] - cornerpoint[0], 0) #x
self.rect.y = round(self.pos[1] - cornerpoint[1], 0) #y
如果我在我的示例中这样做,则表示x_start_position
和y_start_position
未定义。
谢谢!
答案 0 :(得分:1)
您已将Sprite
的当前位置存储在self.rect
中,因此您不需要x_start_position
和y_start_position
。
如果要存储创建Sprite
时使用的原始起始位置,则必须在初始化程序中创建成员:
#TODO: respect naming convention
class sprite_to_place(pygame.sprite.Sprite):
# you can use a single parameter instead of two
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("a_picture.png")
# you can pass the position directly to get_rect to set it's position
self.rect = self.image.get_rect(topleft=pos)
# I don't know if you actually need this
self.start_pos = pos
然后在update
:
def update(self):
# current position is self.rect.topleft
# starting position is self.start_pos
# to move the Sprite/Rect, you can also use the move functions
self.rect.move_ip(10, 20) # moves the Sprite 10px vertically and 20px horizontally