AnimatedSprite
(Topics->Animation->AnimatedSprite)
[Animation]
// Class for animating a sequence of GIFs
class Animation {
PImage[] images;
int imageCount;
int frame;
Animation(String imagePrefix, int count) {
imageCount = count;
images = new PImage[imageCount];
//連番画像ファイルをimageCountで指定された数だけ読み込む
for (int i = 0; i < imageCount; i++) {
// Use nf() to number format 'i' into four digits
// nf()関数を使ってint iを4桁の文字列「0000」に変換しています
String filename = imagePrefix + nf(i, 4) + ".gif";
images[i] = loadImage(filename);
}
}
void display(float xpos, float ypos) {
//クラス内のメンバ変数 frameを使って毎フレーム違う絵を描画します
frame = (frame+1) % imageCount;
image(images[frame], xpos, ypos);
}
int getWidth() {
return images[0].width;
}
}
【補足説明】
Ctrl+K (MacはCmd+K) を押して「Show Sketch Folder」してみましょう。
プログラムのメインである「AnimatedSprite.pde」、クラス「Animation.pde」に加えて「data」フォルダに大量のGIFファイルが有ることを発見できるとおもいます。
☆☆GIF画像を読み込んでアニメーションさせるサンプル。
マウスキーを押すとアニメーションが変わります。
ちなみにsprite(スプライト)とはコンピュータアニメーション用語で「チラチラ動くキャラクタ」のことです。もともと妖精の一種。
[AnimatedSprite]
/**
* Animated Sprite (Shifty + Teddy)
* by James Patterson.
*
* Press the mouse button to change animations.
* Demonstrates loading, displaying, and animating GIF images.
* It would be easy to write a program to display
* animated GIFs, but would not allow as much control over
* the display sequence and rate of display.
*/
Animation animation1, animation2;
float xpos, ypos;
float drag = 30.0;
void setup() {
size(200, 200);
background(255, 204, 0);
frameRate(24);
//アニメーションクラスの初期化時に、読み込むフレームの数を指定
animation1 = new Animation("PT_Shifty_", 38);
animation2 = new Animation("PT_Teddy_", 60);
}
void draw() {
float difx = mouseX - xpos;
if (abs(difx) > 1.0) {
xpos = xpos + difx/drag;
xpos = constrain(xpos, 0, width);
}
// Display the sprite at the position xpos, ypos
if (mousePressed) {
background(153, 153, 0);
animation1.display(xpos-animation1.getWidth()/2, ypos);
} else {
background(255, 204, 0);
animation2.display(xpos-animation1.getWidth()/2, ypos);
}
}
これらのファイル名は「PT_Teddy_0000.gif」〜「PT_Teddy_0059.gif」といった、いわゆる「連番ファイル」になっています。この画像を用意するのは大変ですが、動画編集ソフトやデジカメで撮影したたくさんの画像を使って、同じようなアニメーションつくることができますね。なおデジカメの画像などあまり大きい画像を大量に読むのはメモリを消費するのでおすすめしません。いちどリサイズ(PImage.resize())してから読み込むべきでしょう。