我有这个球员的能力。我只希望玩家能够每5秒使用这个技能一次。我总是可以把这个放在我的游戏循环中:
Update(GameTime gameTime)
{
GamePadState controller = GamePad.GetState(PlayerIndex.One);
cooldown--;
if(cooldown <= 0 && controller.Buttons.A == ButtonState.Pressed)
{
UseAbility();
cooldown = 5000;
}
}但我正在寻找的东西将正好是5秒(相对于5000更新()的),我想要一些比这个野蛮代码更优雅的东西。有什么建议吗?谢谢!
发布于 2014-02-05 00:22:13
您可以使用GameTime变量。你可以试试这样的方法:
float cooldowntime = 0;
Update(GameTime gameTime)
{
GamePadState controller = GamePad.GetState(PlayerIndex.One);
cooldowntime += gameTime.ElapsedGameTime.TotalMilliseconds;
//if you are using XNA 3.1 or earlier, use GameTime.ElapsedRealTime
if(cooldowntime >= 5000 && controller.Buttons.A == ButtonState.Pressed)
{
UseAbility();
cooldowntime = 0;
}
}使用这个更新方法,cooldowntime将获得以毫秒为单位的经过的游戏时间(如果您使用的是XNA3.1,则可以使用ElapsedRealTime,这是“实际”经过的时间。这将是有用的,如果你得到低于60英尺)。然后,如果cooldowntime大于5000 is (5秒),将为一个更新方法启用此功能。如果您想要比GameTime.ElapsedGameTime.TotalMilliseconds更精确,可以使用Stopwatch或DateTime.Now。HTH
注意:如果您每次更新得到60 get,那么ElapsedGameTime应该是非常准确的。
编辑:以减少使用的行数,请尝试如下:
float cooldowntime = 0;
Update(GameTime gameTime)
{
GamePadState controller = GamePad.GetState(PlayerIndex.One);
cooldowntime = (cooldowntime >= 5000 && controller.Buttons.A == ButtonState.Pressed) ? 0 : cooldowntime + gameTime.ElapsedGameTime.TotalMilliseconds;
if (cooldowntime == 0) UseAbility();
// we know to use the ability if cooldowntime = 0 since it will only equal zero
// when cooldowntime >= 5000 and the button is pressed.
}发布于 2017-08-15 19:40:42
简单的例程,只需用需要等待的毫秒数调用它,在调用端只需执行一个if语句,如:-
if(DelayGame(gameTime, 5000))
{
// after 5 seconds
// do this
}这里是:-
private static bool delayFlag = false;
private static double delayTime = 0;
public static bool DelayGame(GameTime gameTime,int milliSeconds)
{
if(delayFlag)
{
if(gameTime.TotalGameTime.TotalMilliseconds >= delayTime)
{
delayFlag = false;
return true;
}
}
else
{
delayFlag = true;
delayTime = gameTime.TotalGameTime.TotalMilliseconds + milliSeconds;
}
return false;
}我在任何地方都使用了静态,所以你不用担心你从哪里调用它,享受和做伟大的游戏
https://stackoverflow.com/questions/21566205
复制相似问题