I’m making a 2d game, and some of the walls are destructible.
There are 5 sprites for that type of wall.
- Normal wall sprite
- Destroyed frame 1
- Destroyed frame 2
- Destroyed frame 3
- Destroyed frame 4
All 5 of these sprites are loaded into a PImage array in setup.
The draw method in my wall class is like this: image(sprites[currentFrame], x, y)
I have a collided flag that is set to true once the player projectile hits it.
What I want it to do is once hit, trigger a 4 frame destruction sequence, where each of the destruction sprites are shown for only one frame
2 Likes
I can give you a system I usually implement when working with sprites:
MainSketch.pde
SpriteHandler standardHandler=new SpriteHandler();
void setup(){}
void draw(){
standardHandler.run();
}
SpriteHandler
class SpriteHandler {
ArrayList<Sprite> sprites=new ArrayList<Sprite>();
SpriteHandler(){
}
void register(Sprite s){
sprites.add(s);
}
void run(){
for(Sprite s:sprites) s.run(s.currframe++);
for(int i=sprites.size()-1;i>=0;i--) if(sprites.get(i).done()) sprites.remove(i);
}
}
Sprite.pde
abstract class Sprite{
int duration=0;
int currframe=0;
boolean forceQuit=false;
boolean done(){
return duration<=(currframe&&duration>0)||forceQuit;
}
void register(){
standardHandler.register(this);
}
abstract void run(int frame);
}
You can make your class extend the Sprite class and implement the run method to draw your sprite.
You just have to set super.duration=4 to signal that your sprite has 4 frames.
Now once you have a collision trigger you can create a new instance of your Sprite and
call the register method on it.
If you want I could send some shorter code that is more inefficent though.
2 Likes
Could you please send me some shorter code? I just wanna get it working before implementing the longer method you provided
Good starting point!
if(collided){
image(sprites[currentFrame], x, y);
currentFrame++;
if(currentFrame>4) currentFrame=4;
}else{
image(wall,x,y);
}
1 Like
This would be a much shorter class that plays the sprite once the Constructor is called
final PApplet enclosing_instance=this;
public class ImageSprite {
int x, y;
ImageSprite(int x, int y) {
this.x=x;
this.y=y;
register();
}
int currentFrame=0;
int duration=4;
void register() {
enclosing_instance.registerMethod("draw", this);
}
public void draw() {
if (currentFrame<duration) run(currentFrame);
else enclosing_instance.unregisterMethod("draw", this);
currentFrame++;
}
void run(int frame) {
//paint your image here
rect(x, y, 10, 10);
}
}
1 Like