Skip to content

Instantly share code, notes, and snippets.

@tedigc
Created September 12, 2016 20:57
Show Gist options
  • Select an option

  • Save tedigc/490630d4c09763d8a9de77fd0cd89bc1 to your computer and use it in GitHub Desktop.

Select an option

Save tedigc/490630d4c09763d8a9de77fd0cd89bc1 to your computer and use it in GitHub Desktop.
Easily reference individual sprites from a spritesheet.
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
/**
* @author brokenbeach
* @since 12/09/2016
*/
public class SpriteSheet {
private Texture tex;
private int nSpritesWide;
private int nSpritesHigh;
private int padding;
private int spriteWidth;
private int spriteHeight;
public SpriteSheet(AssetManager assets, String ref, int nSpritesWide, int nSpritesHigh, int padding) {
tex = assets.get(ref, Texture.class);
this.nSpritesWide = nSpritesWide;
this.nSpritesHigh = nSpritesHigh;
this.padding = padding;
spriteWidth = ((tex.getWidth() - padding) / nSpritesWide) - padding;
spriteHeight = ((tex.getHeight() - padding) / nSpritesHigh) - padding;
}
public TextureRegion getTexture(int index) {
int x = index % nSpritesWide;
int y = index / nSpritesHigh;
int spriteX = x * (spriteWidth + padding) + padding;
int spriteY = y * (spriteHeight + padding) + padding;
return new TextureRegion(tex, spriteX, spriteY, spriteWidth, spriteHeight);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment