- Home /
Proper item usage design
Hi! I'm currently struggling with a following design problem.
The project is a top-down 2D rpg with an item system similar to games like e.g. Terraria/Stardew Valley. Basically there is a item bar on the bottom, you select one item, and use it by clicking somewhere on the screen.
The system was previously defined in such way:
There is a method loading selected item logic (items included data about what type of action they can perform, so a weapon knew if it was a ranged weapon or a melee weapon, tool knew if it was a hammer or an axe etc.). Method was called by clicking on the bottom item bar UI.
public void SelectItem(Item activeItem)
{
switch (activeItem.itemType)
{
case ItemType.Weapon:
//weapon selection logic
break;
case ItemType.Tool:
//tool logic
break;
//cases for other item types
default:
break;
}
}
Item usage was implemented in a following method, it was called by clicking mouse on the screen with mouse position as a parameter.
public void UseItem(Vector2 position)
{
switch (actionType)
{
case ItemActionType.MeleeWeapon:
//MeleeWeaponLogic
break;
case ItemActionType.RangedWeapon:
//RangedWeaponLogic
break;
case ItemActionType.Hammer:
//Hammer logic
break;
case ItemActionType.None:
break;
default:
break;
}
}
After doing some research i went to a conclusion that this approach is bad, because if more items are going to be introduced in the future, both methods will need to be modified and corresponding classes would get very large.
What in your opinion would be a proper approach to this problem? I'm currently thinking about implementing interfaces ISelectable, and IUsable and a class with 2 dictionaries: string, ISelectable, and string, IUsable. Then there would be classes implementing both interfaces for every item type and corresponding actions. At startup the dictionaries would be populated with actions corresponding to every item.
SelectItem and UseItem would just look like:
public void SelectItem(Item item)
{
SomeDictionary[item.name].OnSelect(item);
}
public void UseItem(Item item, Vector2 position)
{
AnotherDictionary[item.name].OnUse(item, position);
}
What do you think about this approach? Do you have any other good ideas or advices?