我想在pygame中做一個拖放機制,我正在部分成功(感謝this one和像this other one這樣的教程的答案)。我使用的機制如下:一旦檢測到按鈕事件(並且只有當鼠標在圖像上時),纔在每個循環中更新圖像的位置。爲此,我通過調用image.get_rect()創建了一個矩形對象,但看起來這個矩形是移動的,圖像的中心位於矩形的右下角。我既附件的代碼的結果:get_rect()在圖像中被移動pygame
import pygame, sys
from pygame.locals import *
FPS = 60
fpsClock = pygame.time.Clock()
def main():
pygame.init()
DS = pygame.display.set_mode((400, 400), 0, 32)
pygame.display.set_caption('Drag-n-drop that cat')
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
catImg = pygame.image.load('cat.png') # I load the image
catImgRectObj = catImg.get_rect() # I create the rect object
catx = 200
caty = 200
catImgRectObj.center = [catx, caty]
IsMousePressed = False
while True:
lastPos = catImgRectObj.center
DS.fill(WHITE)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
IsMousePressed = True
elif event.type == MOUSEBUTTONUP:
IsMousePressed = False
if IsMousePressed and isMouseOverObj(catImgRectObj):
catImgRectObj.center = pygame.mouse.get_pos() #I update the center
else:
catImgRectObj.center = lastPos
pygame.draw.rect(DS, BLACK, catImgRectObj) #draw the rect object
DS.blit(catImg, catImgRectObj.center) #draw the cat.
pygame.display.update()
fpsClock.tick(FPS)
def isMouseOverObj(Obj):
return Obj.collidepoint(pygame.mouse.get_pos())
if __name__ == '__main__':
main()
貓的圖像可以在這裏找到(https://inventwithpython.com/cat.png),它是從[tutorial webpage]下載的(http://inventwithpython.com/pygame/chapter2.html )。 – Miguelgondu