pygame.time.get_ticks() 的问题 [英] Issues with pygame.time.get_ticks()

查看:113
本文介绍了pygame.time.get_ticks() 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏,我需要在路径中每 1350 毫秒后生成一个敌人.而敌人只会在我点击开始按钮后才开始出现.

I have a game where I need an enemy to spawn after every 1350 milliseconds in a path. And the enemies only start coming after I click on the start button.

时间间隔代码:

sendEnemy = 0

def enemy_object_creation(sprite_list, health):
    global sendEnemy

    if pygame.time.get_ticks() >= sendEnemy:
        foe = Enemy(sprite_list, health)
        enemies.add(foe)

        sendEnemy += 1350

现在,当我在大约 5 秒后单击开始按钮时,大量敌人在开始时涌入,然后又开始顺利进入.我点击开始按钮的时间越长,开始时生成的敌人就越多.我不知道该怎么办.

Now here, when I click on the start button after around 5 secs, a bulk of of enemies come flooding at the beginning and then afterwards they again start coming smoothly. The more time I take to click on the start button, the more enemies spawn together at start. I'm not sure what to do about it.

将不胜感激.

推荐答案

在pygame中可以通过调用pygame.time.get_ticks(),它返回自 pygame.init() 被调用.请参阅 pygame.time 模块.

In pygame the system time can be obtained by calling pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. See pygame.time module.

当点击开始按钮时,您需要计算第一个敌人必须出现的时间.

You need to calculate the time when the first enemy will have to spawn, when the start button is clicked.

在全局命名空间中指定 sendEnemy 变量:

Specify the sendEnemy variable in global namespace:

sendEnemy = 0

设置初始时间值,当按钮被点击时:

Set the initial time value, when the button is clicked:

if clicked:
    global sendEnemy
    current_time = pygame.time.get_ticks()
    sendEnemy = current_time 

如果 sendEnemy 大于 0,但小于当前时间,则产生新的敌人:

Spawn new enemies if sendEnemy is greater than 0, but less than the current time:

def enemy_object_creation(sprite_list, health):
    global sendEnemy

    if 0 < sendEnemy <= pygame.time.get_ticks():
        foe = Enemy(sprite_list, health)
        enemies.add(foe)

        sendEnemy += 1350

如果你想阻止敌人生成,设置sendEnemy = 0.

If you want to stop enemies from spawning, set sendEnemy = 0.

或者,您可以根据当前时间计算下一个敌人必须出现的时间.然而,这会导致轻微的不准确,因为代码没有按时运行,而是在几毫秒后运行:

Alternatively you can compute the time when the next enemy will have to spawn, depending on the current time. However, this leads to a slight inaccuracy as the code does not run on time, but a few milliseconds later:

def enemy_object_creation(sprite_list, health):
    global sendEnemy

    current_time = pygame.time.get_ticks()
    if sendEnemy <= current_time:
        foe = Enemy(sprite_list, health)
        enemies.add(foe)

        sendEnemy = current_time + 1350

这篇关于pygame.time.get_ticks() 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆