簡體   English   中英

如何在Pygame中獲得子畫面的位置?

[英]How do I get the position of a sprite in Pygame?

因此,我正在嘗試對鼠標進行編程,使其移動到屏幕上最近的一塊奶酪並吃掉它。 但是,為此,我需要找到其他子畫面的位置/坐標。 那么我如何找到一個精靈在Pygame中的位置? 謝謝!

根據文檔,每個Sprite都需要具有.rect屬性。
請參閱pygame.sprite的文檔:

基本的Sprite類可以將其包含的Sprite繪制到Surface。 Group.draw()方法要求每個Sprite都具有一個Surface.image屬性和一個Surface.rect屬性。

.rect屬性必須由應用程序設置:

再次,我將參考文檔:

子類化Sprite時,請務必先調用基本初始化方法,然后再將Sprite添加到組中。 例如:

 class Block(pygame.sprite.Sprite): # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(color) # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() 

當然,屬性也可以直接設置為sprite對象:

例如

mySprite = pygame.sprite.Sprite()
mySprite.image = pygame.Surface([width, height])
mySprite.rect = mySprite.image.get_rect()

之后,可以隨時從.rect屬性獲取位置。 參見pygame.Rect

例如

topLeftX, tolLeftY = mySprite.rect.topleft
centerX, centerY = mySprite.rect.center

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM