theARTboy
where art meets design
Spritesheets using Processing
Categories: processing

I have been trying out a few new styles for making sprite sheets when using processing. The technique I decided to try was putting each frame of a sprite animation as an image in an array. Then during the render of the animation it is a simple image(frame[currentSprite],x,y) call. Previously, I called either copy or get during the render of each update of the main sketch draw loop.

Using the get method
[java]

/* @pjs preload="imagefile.png"; */

PImage src;
int w = 53;//tile width
int h = 63;//tile height
int cols = 4;
int currentSprite=0;
int totalSprites=12;

PImage frames[];

void setup() {
size(636, 300);
background(255);
src=loadImage("imagefile.png");
smooth();
frames = new PImage[totalSprites];
for (int i = 0; i<frames.length; i++) {
int tx = floor(i%cols)*w;
int ty = floor(i/cols)*h;
frames[i]=src.get(tx, ty, w, h);
}
}

void draw() {
background(255);
for (int i = 0; i<frames.length; i++) {
image(frames[i], i*w, i, w, h);
}
image(frames[currentSprite], mouseX, mouseY);
currentSprite=(currentSprite+1)%totalSprites;
}
[/java]

Using the copy method
[java]
/* @pjs preload="imagename.png"; */
PImage src;
int w = 53;//tile width
int h = 63;//tile height
int cols = 4;
int currentSprite=0;
int totalSprites=12;
PImage tempImage;

PImage frames[];

void setup() {
size(636, 300);
background(255);
src=loadImage("imagefile.png");
smooth();

frames = new PImage[totalSprites];
for (int i = 0; i<frames.length; i++) {
int tx = floor(i%cols)*w;
int ty = floor(i/cols)*h;
PImage ti = createImage(w, h, ARGB);
ti.copy(src, tx, ty, w, h, 0, 0, w, h);
frames[i]=ti;
}
}

void draw() {
background(255);
image(frames[currentSprite], mouseX, mouseY);
currentSprite=(currentSprite+1)%totalSprites;
}
[/java]

Now I am curious how copy compares to get for constructing spritesheet animations. The next method is to compare these to the other method of calling copy each time for each sprite where the sprite has loaded its source in the constructor as shown next
[java]
class Sprite {
PImage src;
int w;// width of tile
int h;// height of tile
int tileX;// x location for the currentTile on the sprite sheet
int tileY;// y location for the currentTile on the sprite sheet
int x;// display x location for rendered sprite
int y;// display x location for rendered sprite
int cols;
int currentSprite;
int totalSprites;

Sprite(String src_, int w_, int h_, int cols_, int totalSprites_){
src=loadImage(src_);
w=w_;
h=h_;
cols=cols_;
totalSprites=totalSprites_;
currentSprite=0;
}

void render(int x_, int y_){
x=x_;
y=y_;
tileX = int(currentSprite%cols)*w;
tileY = int(currentSprite/cols)*h;
copy(src,tileX,tileY,w,h,x,y,w,h);
currentSprite = (currentSprite+1)%totalSprites;
}
}
[/java]

Any feedback of how to get the best performance out of my spritesheets would be appreciated.

Leave a Reply

You must be logged in to post a comment.