如何在pygame中让图像跟随鼠标光标
我的代码如下。这只是一个简单的程序,涉及到二维运动。
bif="C:\\Users\\Andrew\\Pictures\\pygame pictures\\Background(black big).png"
mif="C:\\Users\\Andrew\\Pictures\\pygame pictures\\bullet.png"
import pygame, sys
from pygame.locals import *
pygame.init()
from timeit import default_timer
screen=pygame.display.set_mode((1000,1000),0,32)
background=pygame.image.load(bif).convert()
bullet=pygame.image.load(mif).convert_alpha()
##Lines##
color=(255,255,255)
screen.lock()
pygame.draw.line(background, color, (30,970), (585,970))
pygame.draw.line(background, color, (585,-190), (585,970))
pygame.draw.line(background, color, (30,-190), (30,970))
screen.unlock()
## Horizontal Movement##
x=0
speedx= 0
dmx=0
## Vertical motion##
y=-190
dmy=0
clock=pygame.time.Clock()
speedy= 0
acceleration= 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
我的问题在这里:
elif event.type == pygame.MOUSEBUTTONDOWN:
## Horizontal ##
(mouseX, mouseY) = pygame.mouse.get_pos()
x=mouseX-87
speedx= 0
dmx=0
X1 = mouseX-87
## Vertical ##
y=mouseY-172
dmy=0
speedy= 0
acceleration= 0
Y1 = mouseY-172
elif event.type == pygame.MOUSEBUTTONUP:
(mouseX, mouseY) = pygame.mouse.get_pos()
## Horizontal ##
x=mouseX-87
speedx= 100
dmx=0
X2 = mouseX-87
## Vertical ##
y= mouseY-172
dmy=0
speedy= 1
acceleration= .5
y2 = mouseY - 87
screen.blit(background, (0,0))
screen.blit(bullet, (x, y))
我不知道怎么让子弹跟着鼠标光标移动。当按下鼠标按钮时,子弹会出现并保持静止,不管鼠标光标怎么移动。当松开鼠标按钮时,子弹会立刻出现在那个点上。我该怎么让子弹沿着鼠标光标的路径移动呢?
变量说明: dmx = 在x轴上移动的距离 dmy = 在y轴上移动的距离 其他的变量就比较好理解了。
2 个回答
1
如果你把
event.type == pygame.MOUSEBUTTONUP
改成
event.type == pygame.MOUSEMOTION
,那么它就会跟着你的鼠标移动。
2
你需要在 screen.blit(bullet,(x,y))
这行代码后面加上 pygame.display.update()
这行代码。