python - 如何在第一次单击鼠标时选择一个 Sprite ,然后在第二次单击鼠标的位置创建一个新 Sprite

标签 python pygame

我正在创建一个简单的游戏,要求您能够通过单击来选择一个 Sprite ,然后将您选择的 Sprite 的新实例放置到第二次鼠标单击的位置。

#Creating the sprite
addBarrierButton = Barrier()

addBarrierButton.rect.x=800
addBarrierButton.rect.y=400
all_sprites_list = pygame.sprite.group()
all_sprites_list.add(addBarrierButton)
all_sprites_list.draw(gameDisplay)

#Main loop

while True:
    ev = pygame.event.get()
    for event in ev: 
        if event.type = pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()

        if addBarrierButton.rect.collidepoint(mouse_pos):
            #Here is where I am stuck... I need it to wait for a second 
            #click 
            #and then create a new barrier at the position of that click

主要问题是我找不到在第一次点击后等待第二次点击的方法。

最佳答案

您无需等待第二次点击。您需要能够了解单击时程序是否应该选择 Sprite 或创建一个新 Sprite 。

实现此目的的一种方法是创建一个变量selected_sprite。如果此变量等于None,则意味着单击必须选择一个 Sprite 。如果此变量保存一个 Sprite ,您可以在新位置创建它的副本(或只是一个新 Sprite )。

我重新编写了您的代码以展示如何操作:

addBarrierButton = Barrier()

addBarrierButton.rect.x=800
addBarrierButton.rect.y=400

all_sprites_list = pygame.sprite.group()
all_sprites_list.add(addBarrierButton)
all_sprites_list.draw(gameDisplay)

selected_sprite = None

#Main loop
while True:
    for event in pygame.event.get():
        if event.type = pygame.MOUSEBUTTONDOWN:
            if selected_sprite is None:
                for spr in all_sprites_list:
                    if spr.rect.collidepoint(event.pos):
                        selected_sprite = spr
                        break
            else:
                new_sprite = Barrier()
                new_sprite.image = selected_sprite.image
                new_sprite.rect.x = event.pos[0]
                new_sprite.rect.y = event.pos[1]
                all_sprites_list.add(new_sprite)
                selected_sprite = None

关于python - 如何在第一次单击鼠标时选择一个 Sprite ,然后在第二次单击鼠标的位置创建一个新 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57135363/

相关文章:

python - 如何在变量名中存储具有两个索引的数组?

python - NumPy:用 NaN remove 计算平均值

python - 使用 Python Paramiko 通过 SCP 在两个远程 Linux 服务器之间复制文件

python - Pygame 显示卡尔曼滤波器

python - 从第 2 行读取文件或跳过标题行

python-3.x - python 3 : how to install pygame?

python - Pygame Sprite 双跳

Python pygame 如何设置FPS

python - 我可以在屏幕上移动pygame游戏窗口吗(pygame)

python - 为什么 pygame.sndarray.make_sound 似乎使声音持续时间增加了四倍?