Python 如何在pygame中使用鼠标移动图像?
如何使用pygame在Python中编写由鼠标移动控制图像的代码 我已经试过了:Python 如何在pygame中使用鼠标移动图像?,python,animation,pygame,mouse,Python,Animation,Pygame,Mouse,如何使用pygame在Python中编写由鼠标移动控制图像的代码 我已经试过了: #!/usr/bin/env python # -*- coding: utf-8 -*- import pygame import random pygame.init() size=[800,600] screen=pygame.display.set_mode(size) pygame.display.set_caption("Sub Dice") background_position=[0,0]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
import random
pygame.init()
size=[800,600]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Sub Dice")
background_position=[0,0]
background_image=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\star.png').convert()
card=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\lappy.png').convert_alpha()
card=pygame.transform.smoothscale(card,(130,182))
closeDeckShirt=pygame.image.load('C:\Users\SHIVANGI\Desktop\shivangi project\program\star.png').convert_alpha()
SETFPS=30
zx=0
zy=0
done=False
clock=pygame.time.Clock()
while done==False:
clock.tick(SETFPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.MOUSEBUTTONDOWN:
print('a')
screen.blit(background_image, background_position)
screen.blit(card,[zx,zy])
zx=zx+2
zy=zy+2
pygame.display.flip()
pygame.quit ()
但是,无论我在何处移动鼠标,运动仅限于一个方向。我希望图像向前移动,并由鼠标的运动控制横向运动
此外,我的目标是在orisinal制作一款类似于水上翅膀的游戏。你很快就能完成这项工作了。 我做了一些小的修改 因此,您的程序有两个问题。第一个问题是,您的程序在每个
pygame.event
上移动图像,而不管发生什么事件——您可以通过点击一个键、单击鼠标等方式看到这一点。第二个问题是,您在固定方向上移动图像
我唯一改变的是你的while
循环:
while done==False:
clock.tick(SETFPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.MOUSEBUTTONDOWN:
print('a')
if event.type == pygame.MOUSEMOTION: # We only want to move the image when the mouse is moved.
mouse_position = pygame.mouse.get_pos() # Where is the mouse at?
screen.blit(background_image, background_position)
screen.blit(card, [zx, zy])
zx = mouse_position[0] # mouse_position is in the form [x,y], we only want the x part
zy = mouse_position[1]
pygame.display.flip()
正如您所看到的,Pygame有一个
鼠标。get_pos()
函数,可以实际获取鼠标在屏幕上的位置。这只是一个(x,y)坐标。pygame。MOUSEMOTION
事件有一个rel
属性(相对移动),您可以使用该属性更改x,y
坐标。水平移动只需执行x+=event.rel[0]
,垂直移动只需执行y+=event.rel[1]
您还可以使用if event.buttons[0]:
(1是中间按钮,2是右按钮)检查是否按下了鼠标按钮
要将坐标设置为鼠标位置,可以执行以下操作:x,y=event.pos
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
IMG = pg.Surface((120, 90))
IMG.fill((0, 120, 200))
x = 200
y = 300
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEMOTION:
if event.buttons[0]: # Left mouse button pressed.
x += event.rel[0]
y += event.rel[1]
screen.fill(BG_COLOR)
screen.blit(IMG, (x, y))
pg.display.flip()
clock.tick(60)
pg.quit()
有一件事与Pygame无关—字符串中的文件路径应该使用双精度
`s或正斜杠(
/),否则它们可能会被破坏—因为Python strings.thanx中的scape字符很多。这帮了大忙。