【问题标题】:pygame dragging a background imagepygame拖动背景图像
【发布时间】:2015-10-09 01:14:45
【问题描述】:

这是对以下代码的后续问题。
我注释掉了 y imgPos,所以图像只能向左或向右拖动。但是您可以在任一方向上永久拖动图像。你怎么能设置一个停止点,这样你就不能再左右拖动它了。

我试过 imgPos.clamp_ip(screen)

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)

【问题讨论】:

    标签: pygame


    【解决方案1】:

    为什么不这样做

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-14
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2015-12-23
      • 1970-01-01
      相关资源
      最近更新 更多