首页 > 解决方案 > 如何在 XNA 中倒计时每秒的生命条生命值?

问题描述

我有一个汽车游戏,当汽车跑出马路时,它的生命值会减少。但我想减缓下降速度。我该怎么做?这是当前的代码。

for (int i = 20; i >= 0; i--)
{
    if (car.getPosY() < 450 || car.getPosY() > 500)
    {
        car.hitPoints = car.hitPoints - 1;
        // if (car.hitPoints <= 0) car.active = false;
    }
}

标签: c#xnamonogame

解决方案


但我想减缓下降速度。

您将需要为您的汽车实现一个计时器,如下所示:每当汽车损坏时,它的生命值就会降低,并且在一小段时间内(例如 1 秒或 1000 毫秒)汽车会忽略所有损坏。

我已经在评论中质疑了外循环的使用,所以我不会在这里详述。我没有像您在代码中那样使用循环。

您的car类需要有一个int变量来存储时间(以毫秒为单位),如图所示

class Car
{
    int Timer=0;
    ...//Other stuff you have already
}

接下来改变你的逻辑,如图所示:

if (car.getPosY() < 450 || car.getPosY() > 500)
{
    if(car.Timer==0) //This code happens once per second (according to the Timer value below)
    {
        car.hitPoints = car.hitPoints - 1;
        // if (car.hitPoints <= 0) car.active = false;
    }
    car.Timer += gameTime.ElaspedGameTime.Milliseconds;//Value of time (in milliseconds) elasped from the previous frame
    if(car.Timer >= 1000) //max value of time when damage is ignored. You can change this value as per your liking.
        car.Timer = 0; //Reset the timer
}
else car.Timer = 0; //Reset the timer

我没有测试就输入了这段代码。让我知道是否有任何问题。


推荐阅读