问题描述
我有一个汽车游戏,当汽车跑出道路时,它的健康栏会减少。但我想减慢下降速度。我该怎么做? 这是当前代码。
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;
}
}
解决方法
但我想减缓下降的速度。
您需要为您的汽车实施一个计时器,如下所示:每当汽车损坏时,它的生命值都会降低,并且在一小段时间内(例如 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
我在没有测试的情况下输入了此代码。如果有任何问题,请告诉我。