Here are two common/easy ways. One would be to rely on static getters or singleton instances. You can extend this however you see fit; e.g. storing your textures by a String identifier in a hash map.
1 2 3 4 5 6 7 8
| MyEntity { Texture texture;
public MyEntity() { this.texture = MyResources.getInstance().getMyTexture(); } } |
Another common solution is to pass the single texture to the entity when you create it:
1 2 3 4 5 6 7
| MyEntity { Texture texture;
public MyEntity(Texture texture) { this.texture = texture; } } |
To draw a "sub image" of a texture (i.e. render a particular sprite in a sheet), you need to define your texcoords properly. With slick-util, you might define an Image2D/Sprite class that holds the normalized texture offsets and width/height that will be passed to glTexCoord2f:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public Image2D(Texture texture) { this.texture = texture; this.normalizedWidth = texture.getWidth(); this.normalizedHeight = texture.getHeight(); this.width = texture.getImageWidth(); this.height = texture.getImageHeight(); this.centerX = width / 2f; this.centerY = height / 2f; }
public Image2D getSubImage(float x, float y, float width, float height) { float tx = ( x / this.width * normalizedWidth ) + textureOffsetX; float ty = ( y / this.height * normalizedHeight ) + textureOffsetY; float tw = width / this.width * normalizedWidth; float th = height / this.height * normalizedHeight; Image2D img = copy(); img.textureOffsetX = tx; img.textureOffsetY = ty; img.width = width; img.height = height; img.normalizedWidth = tw; img.normalizedHeight = th; img.centerX = width / 2f; img.centerY = height / 2f; return img; } |