/*
 * Animation.java
 *
 * Created on May 14, 2008, 1:36 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package medusa.example;

import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

/**
 *
 * @author Sean
 */
public class Animation {
    
    private ArrayList frames;
    private int currentFrameIndex;
    private long animTime;
    private long totalDuration;
    
    /** Creates a new instance of Animation */
    public Animation() {
        frames=new ArrayList();
        totalDuration=0;
        start();
    }
    
    public synchronized void addShape(Shape shape, long duration){
        totalDuration+=duration;
        frames.add(new AnimFrame(shape, totalDuration));
    }
    
    public synchronized void start(){
        animTime=0;
        currentFrameIndex=0;
    }
    
    /**
     * Updates this animation's current shape (frame)
     * if necessary
     */
    public synchronized void update(long elapsedTime){
        if (frames.size()>1){
            animTime+=elapsedTime;
            
            if (animTime >= totalDuration){
                animTime=animTime % totalDuration;
                currentFrameIndex=0;
            }
            
            while (animTime > getFrame(currentFrameIndex).endTime){
                currentFrameIndex++;
            }
            
        }
        
        
    }
    
    /**
     * Get this animation's current shape. Returns null if this animation has no shape
     */
    public synchronized Shape getShape(){
        if (frames.size() == 0){
            return null;
        }
        else {
            return getFrame(currentFrameIndex).shape;
        }
    }
    
    private AnimFrame getFrame(int i){
        return frames.get(i);
    }
    
    private class AnimFrame{
        Shape shape;
        long endTime;
        
        public AnimFrame(Shape shape, long endTime){
            this.shape=shape;
            this.endTime=endTime;
        }
    }
    
    public void initDefault(){
        int w=10;
               int h=10;
        Rectangle2D.Double rect=new Rectangle2D.Double(0,0,w,h);
        //addShape(rect,2000);
        for (int i=0;i<10; i++){
            addShape(new Rectangle2D.Double(0,0,w,h-i),200);
        }
         for (int i=0;i<10; i++){
            addShape(new Rectangle2D.Double(0,0,w,i),200);
        }
                
    }
   
}

 

Ads help maintain this website.