Files
processing4/java/examples/Topics/Animation/AnimatedSprite/applet/AnimatedSprite.java
benfry eb64b2d4fc
2011-01-26 19:22:19 +00:00

87 lines
2.0 KiB
Java

import processing.core.*;
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.zip.*;
import java.util.regex.*;
public class AnimatedSprite extends PApplet {
/**
* 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.0f;
public void setup() {
size(200, 200);
background(255, 204, 0);
frameRate(24);
animation1 = new Animation("PT_Shifty_", 38);
animation2 = new Animation("PT_Teddy_", 60);
}
public void draw() {
float difx = mouseX - xpos;
if (abs(difx) > 1.0f) {
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);
}
}
// 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];
for (int i = 0; i < imageCount; i++) {
// Use nf() to number format 'i' into four digits
String filename = imagePrefix + nf(i, 4) + ".gif";
images[i] = loadImage(filename);
}
}
public void display(float xpos, float ypos) {
frame = (frame+1) % imageCount;
image(images[frame], xpos, ypos);
}
public int getWidth() {
return images[0].width;
}
}
static public void main(String args[]) {
PApplet.main(new String[] { "AnimatedSprite" });
}
}