用时间和金钱的百分比计算浮动

时间:2016-03-22 15:56:47

标签: c# math

我想在游戏中制作结构的构建过程。如果时间百分比(timer/neededTime*100)小于货币百分比(player.money/neededMoney*100),则此过程才会继续。每一帧,特定金额,应从player.money减少,以便整个过程的结束money.player = money.player - neededMoney。我不知道如何计算每帧从钱中减少的浮动数。

1 个答案:

答案 0 :(得分:0)

您需要的是减去neededMoney每个neededTime单位的一部分?

neededTime个单位,我假设是一个非负非零整数值,您需要减去neededMoney/neededTime

每帧,代码看起来像这样。假设framesPerSecond是常数,neededTime是秒。

var secondsPerFrame = 1/(float)framesPerSecond;
var moneyPerSecond = neededMoney/(float)neededTime;
var moneyPerFrame = moneyPerSecond * secondsPerFrame;
//The above can be rewritten as:
//var moneyPerFrame = neededMoney/(float)neededTime/(float)framesPerSecond);

if (player.money >= moneyPerFrame)
{
    player.money -= moneyPerFrame;
}

更新以支持更改帧速率

我写了一个应该能够处理不断变化的帧率和可用资金不足的课程。在每个帧(或适当的时候),调用GetValueToSubtract()方法。

public class BuildingExpenseCalculator
{
    private readonly IAccount _account;
    private readonly float _moneyNeeded;
    private readonly float _spendingRate;

    private float _moneyNeededRemaining;
    private DateTime _lastSubtract;

    public BuildingExpenseCalculator(IAccount account, float moneyNeeded, TimeSpan timeNeeded)
    {
        _account = account;
        _moneyNeeded = moneyNeeded;

        _spendingRate = moneyNeeded/(float) timeNeeded.TotalSeconds;
    }

    public void StartCalculation()
    {
        _lastSubtract = DateTime.Now;
        _moneyNeededRemaining = _moneyNeeded;
    }

    public float GetValueToSubtract()
    {
        var now = DateTime.Now;
        var timePassedSinceLastSubtract = now - _lastSubtract;
        var moneyToSubtractSinceLast = (float)(_spendingRate*timePassedSinceLastSubtract.TotalSeconds);

        // Ensure we do not exceed the remaining money that is needed.
        moneyToSubtractSinceLast = Math.Min(moneyToSubtractSinceLast, _moneyNeededRemaining);

        // Ensure we do not spent more money than is available in the account.
        moneyToSubtractSinceLast = Math.Min(moneyToSubtractSinceLast, _account.AvailableMoney);

        // Update for next iteration.
        _moneyNeededRemaining -= moneyToSubtractSinceLast;
        _lastSubtract = now;

        return moneyToSubtractSinceLast;
    }
}

public interface IAccount
{
    float AvailableMoney { get; set; }        
}