Pregunta

I am working on a game and I have a sprite sheet of my character, but obviously I just want to draw 1 frame of my characters animations at a time. Is it possible to do so using the image() function?

here is the code (this is for a specific person helping me out)

    'PImage spritesheet;
    int DIM_X = 13;
    int DIM_Y = 1;
    PImage[] sprites =  new PImage[DIM_X*DIM_Y];

    void setup() {
     size(300, 300);
     imageMode(CENTER);
     spritesheet = loadImage("PlayerSprites.png");
     int W = spritesheet.width/DIM_X;
     int H = spritesheet.height/DIM_Y;
     for (int i=0; i<sprites.length; i++) {
      int x = i%DIM_X*W;
      int y = i/DIM_Y*H;
      sprites[i] = spritesheet.get(x, y, W, H);
    }
    frameRate(10);
  }

 void draw() {

background(0,0,0);    
image(sprites[frameCount%sprites.length], width/2, height/2);

}'
¿Fue útil?

Solución

The following code will do what you need:

PImage spritesheet;
int DIM_X = 6;
int DIM_Y = 5;
PImage[] sprites = new PImage[DIM_X*DIM_Y];

void setup() {
  spritesheet = loadImage("http://payload23.cargocollective.com/1/6/200359/2773164/player_7.png");
  size(300, 300);
  imageMode(CENTER);
  int W = spritesheet.width/DIM_X;
  int H = spritesheet.height/DIM_Y;
  for (int i=0; i<sprites.length; i++) {
    int x = i%DIM_X*W;
    int y = i/DIM_Y*H;
    sprites[i] = spritesheet.get(x, y, W, H);
  }
  frameRate(10);
}

void draw() {
  background(0,0,0);
  image(sprites[frameCount%sprites.length], width/2, height/2);
}

There are some things you need to keep in mind:

  • DIM_X and DIM_Y represent how many sprites along x and y are there on your sprite sheet. So you need to change those numbers accordingly.
  • Also the PImage is being taken from the internet so, obviously, you need to change the String for loadImage().
  • This is imperfect. You need to tweak it to fit your needs. For example, in the sprite sheet that I used, the last row only has three instances of the character which results in flickering in the animation. You need to make sure to compensate for these things in your code or make your sprite sheet uniform throughout.
  • If you have a sprite sheet with only 1 row. Change this line: int y = i/DIM_Y*H; to int y = 1 to reflect that the number of rows does not change.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top