简体   繁体   English

pygame拖动背景图片

[英]Pygame drag background image

I am trying to make my background image move in the opposite direction as the mouse is moving when it is clicked. 我试图使背景图像与单击鼠标时的移动方向相反。 So it looks like you are dragging the screen left and right, like you can see in many mobile apps. 因此,就像您在许多移动应用程序中看到的那样,您似乎在左右拖动屏幕。 Does anyone have a simple way of doing this? 有人有这样做的简单方法吗?

What you need is to detect the event type, such as MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION . 您需要检测事件类型,例如MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION
When you detected a mouse motion, check if it's clicked using the event.buttons attribute. 当您检测到鼠标移动时,请使用event.buttons属性检查是否单击了event.buttons Here's my implement: 这是我的工具:

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)

You may need to read: Pygame event document 您可能需要阅读: Pygame事件文档

I'm guessing it's meant to be a raw SDL wrapper. 我猜这是要成为原始的SDL包装器。 You'll need to code it yourself. 您需要自己编写代码。 Check if the mouse is down, and if so, track it using something like: 检查鼠标是否按下,如果是这样,请使用类似以下的命令进行跟踪:

AmountMoved = ThisFrameMousePosition - LastFrameMousePosition;

Then add 'AmountMoved' to the position of the background image. 然后将“ AmountMoved”添加到背景图像的位置。 If it's going in the wrong directions which you want, subtract AmountMoved instead. 如果前进方向错误,请减去AmountMoved。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM