Search code examples
javastringlibgdxspriteconverters

How to convert a string to a sprite?


I need advice for a game I am making. I have 16 sprites that can be positioned at runtime in 43 positions. For each position I made a string that will contain the sprite that will be positioned in that position. How can I convert the string to the sprite name so I can add an action to that sprite later? If I want to add if statements to check which of those 16 sprites is in each position will take almost 700 ifs. Is there a way to convert a string to a sprite?


Solution

  • You have sprite's numbered?

    If yes then the simple solution is to have string hash code mod by the sprite counts. Unfortunately you need to keep a map to store which string is mapped to which sprite.

    Example:

    int spriteCount = 16:
    Map strMap = new HashMap();//add type
    String str = incomintStr;
    int hashStr = incomingStr.hashCode();
    int location = hashStr % spriteCount;//a number less than the remaining counts
    map.put(str,location);
    sprite[location].put(str); 
    spriteCount = spriteCount -1;