Im currently using a very crappy method to load sprites and was wondering if anyone can point me to some documentation on how to create a nice class to load some tiles from.
- john
Im currently using a very crappy method to load sprites and was wondering if anyone can point me to some documentation on how to create a nice class to load some tiles from.
First, some basics: What framework are you even using?
I have been building my own from scratch
Stuff a SpriteSheet class needs:
// constructor
(Image, Dimension tileSize) -> SpriteSheet
// indexing function to get the subimages
(Int index) -> Image
// the subimages are defined via rectangles, so we need a index-to-rectangle mapping:
private (Int index) -> Rectangle
// this will involve linear interpolation over both dimensions and the size of each subimage as defined in the constructor
// your library of choice should provide a rectangle-to-subimage mapping, so plug it in
Try to break down your problems into functions and dependencies, your life will be easier.
What I’m saying is, “is it based on Java2d or Opengl?”
Java2d
You could load the Spritesheet as a buffered image, determine all your rectangles as @BurntPizza said, and then use:
BufferedImage sprite = image.getSubimage(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
// rectangle is a given Rectangle object, image is the loaded image
Edit: If you just want a simple code snippet to look at, here’s a simple spritesheet class: http://pastebin.java-gaming.org/5c42f80441819
Note: it only works with the image being evenly divided into sections of Dimension spriteSize
CopyableCougar4
Ive written some code for this , it returns a vertex2d object which is simply a container object with x , y ,u , v;
spritesheet:
package com.lcass.graphics.texture;
import org.lwjgl.opengl.GL11;
public class spritesheet {
private Texture tex;
private float x,y,ex,ey,width,height;
public spritesheet(String location){
tex = Texture.loadTexture(location);
this.width = tex.width;
this.height = tex.height;
}
public spritecomponent getcoords(int x, int y, int ex,int ey){
spritecomponent temp= new spritecomponent();
this.x = x/width;
this.y = y/height;
this.ex = ex/width;
this.ey = ey/height;
temp.set(this.x, this.y, this.ex, this.ey, tex);
return temp;
}
public Texture gettexture(){
return tex;
}
}
then spritecomponent
package com.lcass.graphics.texture;
public class spritecomponent {
public void set(float x, float y, float ex, float ey,Texture t){
this.x = x;
this.y = y;
this.ex = ex;
this.ey = ey;
this.t = t;
}
public float x,y,ex,ey;
public Texture t;
}
Simple and easy to use.
You just need to know how to load in textures , the rest is quite simple where ex ey are the end values x y are the beggining values and T is a texture object containing the width height and id of the texture object.
OP said that he is working with Java2d, which means no GL commands or texture objects.
CopyableCougar4