Search code examples
javastringlibgdxspriteconverters

java - How to convert a string to a sprite?


I need an 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 wich 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;