一组动画
上一节我们实现了sprite的单个行为的动画,但是我们知道,在游戏中某个角色可能有多个行为,比如idle,走,跳,跑等。
那么我们能否封装一个类,来表达一个sprite各种行为动画呢
下面这个Animator类就能实现我们的需求。
Animator类里包含一个HashMap,其key是一个字符串名字即(idle,walk,jump)这种。值是我们上一节的Animation对象。
Animator类和我们上一节的Animation很像,使用前要调用setAnimation方法,根据传入的name,取得当前要播放的动画对象。
比如setAnimation("walk").
完整代码如下:
package sprite; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; public class Animator extends Transform implements ActionListener{ private HashMap<String, Animation> _frames; private Timer _tm; private int _currentFrame = 0; private int _maxFrame = 0; private Animation _currentAnim; public Animator(){ super(); _frames = new HashMap<String, Animation>(); _tm = new Timer(120,this); _tm.start(); } public void addAnimation(Animation anim, String name){ _frames.put(name,anim); } public void setAnimation(String name){ if(_frames.get(name)!=null){ _currentFrame = 0; _currentAnim = _frames.get(name); _maxFrame = _currentAnim.getFrameCount()-1; }else{ System.out.println("ERROR: Animation Name "+name); } } public void show(Graphics2D g){ if(_currentAnim.getImages().get(_currentFrame) != null){ Image img = _currentAnim.getImages().get(_currentFrame); g.drawImage(img.getImage(),getTransform(),null); }else{ System.out.println("ERROR: Animation NULL"); } } @Override public void actionPerformed(ActionEvent e) { _currentFrame++; if(_currentFrame>_maxFrame){ _currentFrame = 0; } } public int getCurrentFrame(){ return _currentFrame; } public int getMaxFrame(){ return _maxFrame; } }
而Animation对象则变得很简洁
package sprite; import java.util.ArrayList; public class Animation{ private ArrayList<Image> _images; private int _frames; public Animation(ArrayList<Image> images){ super(); _images = images; _frames = images.size(); } public int getFrameCount(){ return _frames; } public ArrayList<Image> getImages(){ return _images; } }
测试一下
GameApp修改如下:
1.定义一个Animator对象
private Animator animator = new Animator();
2.添加2个Animation对象到animator
Animation hound = new Animation(images); animator.addAnimation(hound,"dog"); animator.setAnimation("dog"); ArrayList<Image> imagesJasmin = new ArrayList<Image>(); for(int k = 2; k < 8; k++){ Image img = new Image("res/jasmin/00" + k + ".png"); imagesJasmin.add(img); } Animation heroJasmin = new Animation(imagesJasmin); animator.addAnimation(heroJasmin,"hero");
3.按下左右箭头切换动画
if(_input.isKeyUp(KeyEvent.VK_RIGHT)) { System.out.println("VK_RIGHT"); animator.setAnimation("hero"); } else if(_input.isKeyUp(KeyEvent.VK_LEFT)) { animator.setAnimation("dog"); System.out.println("VK_LEFT"); }
4.最后别忘了animator.show(g);
animator.show(g);
如果您迷路了请看这里: