我想在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