繁体   English   中英

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

[英]How to make an image follow the mouse cursor in pygame

我的代码印在下面。 这只是一个具有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轴上移动的距离其余的内容不言自明。

您需要在语句screen.blit(bullet,(x,y))之后添加语句pygame.display.update() screen.blit(bullet,(x,y))

如果你改变

event.type == pygame.MOUSEBUTTONUP

至,

event.type == pygame.MOUSEMOTION ,它将跟随您的鼠标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM