以下是对以下代码的跟进问题 我注释掉了y imgPos,因此只能向左或向右拖动图像。但是你可以在任何一个方向上永久拖动图像。你如何设置一个停止点,这样你就不能再向左和向右拖动它。
我试过imgPos.clamp_ip(屏幕)
import pygame
from pygame.locals import *
pygame.display.init()
screen = pygame.display.set_mode((800, 600))
img = pygame.image.load('sky.png')
imgPos = pygame.Rect((0, 0), (0, 0))
LeftButton = 0
while 1:
for e in pygame.event.get():
if e.type == QUIT: exit(0)
if e.type == MOUSEMOTION:
if e.buttons[LeftButton]:
# clicked and moving
rel = e.rel
imgPos.x += rel[0]
#imgPos.y += rel[1]
screen.fill(0)
screen.blit(img, imgPos)
pygame.display.flip()
pygame.time.delay(30)
答案 0 :(得分:0)
为什么不这样做呢
if e.type == MOUSEMOTION:
if e.buttons[LeftButton]:
# clicked and moving
rel = e.rel
imgPos.x += rel[0]
if imgPos.x < MIN_X:
imgPos.x = MIN_X
elif imgPos.x > MAX_X:
imgPos.x = MAX_X
如果你想让它更整洁一点,你可以将它包装在pygame.Rect
对象中,这也可以更容易地为imgPos.y
border = pygame.Rect(MIN_X, MIN_Y, WIDTH, HEIGHT)
if e.type == MOUSEMOTION:
if e.buttons[LeftButton]:
# clicked and moving
rel = e.rel
imgPos.x += rel[0]
if imgPos.left < border.left:
imgPos.left = border.left
elif imgPos.right > border.right:
imgPos.right = border.right