我有这个代码:
un = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
x1, y1 = pygame.mouse.get_pos()
Player(PlayerX, PlayerY)
pygame.display.update()我想在两种情况下使用鼠标x和鼠标y坐标来查看哪一个更大,但我不能真正使用坐标,因为它们中的一个总是被证明是未定义的,我该如何实现这一点呢?
发布于 2021-11-17 22:49:38
您可以为鼠标设置一个默认位置,该位置与指向前方的弹弓相对应。让它像这样:
defx = 30 #Default x coordinate example
defy = 30 #Default y coordinate example然后,当你进行比较时,你就会像你说的那样得到不同之处。但是如果你需要最后一个鼠标位置,你也可以这样做:
lx, ly, x, y = 0, 0, 0, 0 #It's probably better to use two arrays here
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
lx, ly = x, y #This makes so that lx and ly are the last frame values of x and y
x, y = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
x1, y1 = pygame.mouse.get_pos()这样,您可以使用lx和ly作为最后的x和y值。我真的不明白你想在鼠标上方部分做什么,但是你可以用lx1和ly1做同样的事情。
发布于 2021-11-18 00:45:52
您正在执行的操作将不起作用,因为您不能同时打开鼠标和按下鼠标。你能做的就是在鼠标按下的时候保存一次鼠标的位置。让我们称其为heldDownMomentPosition。然后,在鼠标按键事件之后的任何时间,您都可以计算heldDownMomentPosition和当前鼠标位置之间的差异。这将给你弹弓子弹需要去的方向。我在不久前制作的一个游戏中使用了这个机制,下面是一些修改,以使其最小化。它也有一个简单的拖拽来使它停止。
import pygame
window = pygame.display.set_mode((600, 600))
slingShotBullet = pygame.Surface((40, 40)).convert()
slingShotBullet.fill((255, 255, 255))
pos = [300, 300]
vel = [0, 0]
clock = pygame.time.Clock()
heldDownMomentPosition = None
while True:
dt = clock.tick(60) * 0.001 #delta time in s
mousePressed = pygame.mouse.get_pressed()
mousePos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if heldDownMomentPosition is None:
if pygame.Rect(*pos, 40, 40).collidepoint(mousePos):
heldDownMomentPosition = pos[0] + 20, pos[1] + 20
if event.type == pygame.MOUSEBUTTONUP:
if heldDownMomentPosition is not None:
vel = [heldDownMomentPosition[0] - mousePos[0], heldDownMomentPosition[1] - mousePos[1]]
heldDownMomentPosition = None
vel[0] *= 0.99
vel[1] *= 0.99
pos[0] += vel[0] * dt
pos[1] += vel[1] * dt
window.fill(0)
window.blit(slingShotBullet, pos)
if heldDownMomentPosition is not None:
pygame.draw.line(window, (255, 0, 0), mousePos, heldDownMomentPosition, 2)
pygame.display.flip()https://stackoverflow.com/questions/70012140
复制相似问题