2015-10-18 125 views
0

是否有可能将雪碧放置在我点击的位置?Pygame-雪碧设置位置与鼠标点击

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_positiony_start_position没有定义。

谢谢!

回答

1

您存储Sprite的当前位置已经在self.rect,因此您不需要x_start_positiony_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 
+0

好。但是仍然无法设置精灵的位置,我点击了它。在我能检查鼠标在主循环中的位置之前,我必须定义我的Sprite的位置。 – Holla

+0

所以,只需将您的主循环中精灵的位置设置为鼠标位置即可。问题在哪里? – sloth

+0

问题是,我想用鼠标点击鼠标的位置在屏幕上创建精灵。所以如果我正确理解你的解决方案,这个精灵已经放置在地图'pos'的位置上,并且它会被移动。想象一下,在战略游戏中放置一座建筑物,那就是我所需要的。但是,非常感谢帮助我:) – Holla