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.