如何在pygame中使图像跟随鼠标光标

时间:2014-10-19 13:57:38

标签: python pygame mouse

我的代码打印在下面。它只是一个具有2D运动的简单程序。

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 个答案:

答案 0 :(得分:1)

您需要在语句pygame.display.update()

之后添加语句screen.blit(bullet,(x,y))

答案 1 :(得分:0)

如果你改变了

event.type == pygame.MOUSEBUTTONUP

to,

event.type == pygame.MOUSEMOTION,它会跟随你的鼠标。