Hi. I'm implementing damage formula class for rpg game with Unity3D.
This class reads formula data from json file and parse it using ExpressionParser(http://wiki.unity3d.com/index.php/ExpressionParser).
And keep it in dictionary for entire game life cycle.
When it needs to calculate damage amount, call calculating function then return amount.
Here is my json data and code.
{
"name" : "normalAttack",
"formula": "attr * weaponAtk"
}
public class DamageFormula: MonoBehaviour {
private static DamageFormula instance;
private Dictionary formulaDictionary;
private ExpressionParser expressionParser;
public static DamageFormula Instance
{
get
{
return instance;
}
}
void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this;
formulaDictionary = new Dictionary();
StreamReader reader = new StreamReader("Assets/DamageFormula.json");
string json = reader.ReadToEnd();
DamageFormulaParser parser = new DamageFormulaParser();
parser = JsonUtility.FromJson(json); // TODO :: modify json format to contain many formula
formulaDictionary.Add(parser.name, parser.formula);
expressionParser = new ExpressionParser();
}
else if(instance != this)
{
DestroyImmediate(gameObject);
}
}
public float CalculateDamage(GameObject actor, string name)
{
float ret = 0f;
float attr = 0f; // attr of actor. actor.GetAttribute();
float weaponAtk = 0f; // actor.weapon.atk;
string formula;
formulaDictionary.TryGetValue(name, out formula);
Assert.IsNotNull(formula);
Expression exp = expressionParser.EvaluateExpression(formula);
exp.Parameters["attr"].Value = attr;
exp.Parameters["weaponAtk"].Value = weaponAtk;
ret = (float)exp.Value;
return ret;
}
}
[Serializable]
public class DamageFormulaParser
{
public string name;
public string formula;
}
The reason why I implemented like this is to avoid hard coding formula and to fix it easily.
Later I am about to add more complicated formula(ex. skill attack damage) and modifier which comes from actor's buff effect.
I want to hear any advice or opinion for improvement of my programming.
↧