Pygame drag background image

2019-05-28 22:07发布

问题:

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?

回答1:

What you need is to detect the event type, such as MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION.
When you detected a mouse motion, check if it's clicked using the event.buttons attribute. 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



回答2:

I'm guessing it's meant to be a raw SDL wrapper. 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. If it's going in the wrong directions which you want, subtract AmountMoved instead.



标签: python pygame