游戏中常用的Animation类,这是一个较完美的实现

 感觉是一个完美的实现,如果觉得哪地方不好,请指出,共同进步

 /**

    The Animation class manages a series of images (frames) and

    the amount of time to display each frame.

*/

public class Animation {

 

    private ArrayList frames;

    private int currFrameIndex;

    private long animTime;

    private long totalDuration;

 

 

    /**

        Creates a new, empty Animation.

    */

    public Animation() {

        this(new ArrayList(), 0);

    }

 

 

    private Animation(ArrayList frames, long totalDuration) {

        this.frames = frames;

        this.totalDuration = totalDuration;

        start();

    }

 

 

    /**

        Creates a duplicate of this animation. The list of frames

        are shared between the two Animations, but each Animation

        can be animated independently.

    */

    public Object clone() {

        return new Animation(frames, totalDuration);

    }

 

 

    /**

        Adds an image to the animation with the specified

        duration (time to display the image).

    */

    public synchronized void addFrame(Image image,

        long duration)

    {

        totalDuration += duration;

        frames.add(new AnimFrame(image, totalDuration));

    }

 

 

    /**

        Starts this animation over from the beginning.

    */

    public synchronized void start() {

        animTime = 0;

        currFrameIndex = 0;

    }

 

 

    /**

        Updates this animation's current image (frame), if

        neccesary.

    */

    public synchronized void update(long elapsedTime) {

        if (frames.size() > 1) {

            animTime += elapsedTime;

 

            if (animTime >= totalDuration) {

                animTime = animTime % totalDuration;

                currFrameIndex = 0;

            }

 

            while (animTime > getFrame(currFrameIndex).endTime) {

                currFrameIndex++;

            }

        }

    }

 

 

    /**

        Gets this Animation's current image. Returns null if this

        animation has no images.

    */

    public synchronized Image getImage() {

        if (frames.size() == 0) {

            return null;

        }

        else {

            return getFrame(currFrameIndex).image;

        }

    }

 

 

    private AnimFrame getFrame(int i) {

        return (AnimFrame)frames.get(i);

    }

 

 

    private class AnimFrame {

 

        Image image;

        long endTime;

 

        public AnimFrame(Image image, long endTime) {

            this.image = image;

            this.endTime = endTime;

        }

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值