繁体   English   中英

基于Python和图块的游戏:限制玩家的移动速度

[英]Python and tile based game: limiting player movement speed

我一直在使用Python和Pyglet库整理基于等距图块的RPG。 但是,我遇到了以下问题:

我的玩家移动是基于由图块组成的三维数组上的位置。 为了限制移动速度,我使用了一个全局变量:TILE_TO_TILE_DELAY = 200。

TILE_TO_TILE_DELAY应该是玩家从一个图块移动到另一个图块所花费的时间(以毫秒为单位)。 在这段时间内,他们应该无法做出新的动作。

我一直在使用的系统是我有一个计时器类,如下所示:

import time

def GetSystemTimeInMS(): #Return system time in milliseconds
    systime = round((time.clock()*1000), 0)
    return systime

class Timer:
def __init__(self,time):
    #time = time for which the timer runs
    self.time = time
    self.start_time = 0
    self.stop_time  = 0

def StartTimer(self):
    #start_time = time at which the timer was started
    self.start_time = GetSystemTimeInMS()
    self.stop_time  = self.start_time + self.time

def TimerIsStopped(self):
    if GetSystemTimeInMS() >= self.stop_time:
        return True
    else:
        return False

播放器类具有一个Timer对象:

self.MoveTimer = Timer(TILE_TO_TILE_DELAY)

当播放器按下W键时,会调用一个函数来检查player.MoveTimer.TimerIsStopped()。 如果返回True,它将调用player.MoveTimer.StartTimer()并开始新的移动到下一个位置。

在偶数循环中,将update(dt)函数设置为每秒发生30次:

def update(dt):
    if player.MoveTimer.TimerIsStopped()
        player.UpdatePosition()

pyglet.clock.schedule_interval(update, 1/30)

现在,按照我的逻辑,update(dt)应该每秒检查30次,是否过去了足够的时间来保证玩家有新的动作事件。 但是,由于某些原因,玩家在较低的FPS时移动得更快。

当我的FPS大约为30时,播放器的移动速度要快于瓷砖精灵较少的区域,从而将帧率提高到60。在FPS较高的区域,根据我的测量,播放器的移动速度实际上几乎快了一倍。

经过一天的搜索,我只是无法弄清楚,也没有从互联网上找到任何东西。 一些帮助将不胜感激。

编辑:启动MoveTimer的代码:

def StartMovement(self, new_next_pos):
    self.RequestedMovement = False
    if self.GetCanMoveAgain():

        self.SetNextPos(new_next_pos)
        self.SetMoveDirection(self.GetDirection())


        #Start the timer for the movement
        self.MoveTimer.StartTimer()
        self.SetIsMoving(True)
        self.SetStartedMoving(True)

        self.SetWalking(True)

        self.SetNeedUpdate(True)

        self.MOVE_EVENT_HANDLER.CreateMoveEvent()

GetCanMoveAgain()返回player.can_move_again的值,该值由update(dt)中的UpdatePosition()设置回True。

好吧,我已经解决了这个问题,但是我仍然不确定是什么原因造成的。 也许这是毫秒级的舍入误差,这与FPS较高时对时钟进行更多检查有关。 无论如何,解决方案:

我决定不使用系统时钟,而是决定在其更新函数中使用Pyglet自己的“ dt”参数:

dt参数给出秒数(由于等待时间,负载和计时器的不准确性,这可能会比请求的间隔稍长一些或更小)。

新计时器如下所示:

class dtTimer: #A timer based on the dt-paremeter of the pyglet event loop
def __init__(self,time):
    self.time = time
    self.time_passed = 0

def StartTimer(self):
    self.time_passed = 0

def UpdateTimer(self, dt):
    self.time_passed += dt*1000

def GetTime(self):
    return self.time

def GetTimePassed(self):
    if not self.TimerIsStopped():
        return self.time_passed
    else:
        return 0

def TimerIsStopped(self):
    if self.time_passed > self.time:
        return True
    else:
        return False

当循环尝试更新玩家的位置时,如果TimerIsStopped返回false,则将dt简单地添加到计时器的self.time_passed中。 这已解决了该问题:玩家移动所需的时间现在是恒定的。

感谢您关注我的问题。

暂无
暂无

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

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