コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】ラップアラウンド関数を定義する

ソースコード

public static class MathfUtils
{
    public static int Wrap( int value, int min, int max )
    {
        int n = ( value - min ) % ( max - min );
        return n >= 0 ? n + min : n + max;
    }
}

使い方

MathfUtils.Wrap( 0, 0, 3 ) // 0
MathfUtils.Wrap( 1, 0, 3 ) // 1
MathfUtils.Wrap( 2, 0, 3 ) // 2
MathfUtils.Wrap( 3, 0, 3 ) // 0
MathfUtils.Wrap( 4, 0, 3 ) // 1
MathfUtils.Wrap( 5, 0, 3 ) // 2

関連記事