今天做到一个效果, 要求每个对象可能会同时有几个减血的效果, 就是一个减血的数值在向上飘
因为最大数值不确定, 因此Vector成为首选
我先贴下基本代码吧:
/** */ /** * 减血效果的管理者 * @author ok * */ public class DecBloodManager ... { Vector vBloods; public DecBloodManager(Tank tank) ...{ vBloods = new Vector(); } /** *//** * 渲染所有减血 * @param g * @param ox * @param oy */ public void render(Graphics g, int ox, int oy) ...{ DecBlood db = null; for(int i = vBloods.size(); --i >= 0;) ...{ db = (DecBlood)vBloods.elementAt(i); db.render(g, ox, oy); } } public void add(DecBlood db) ...{ vBloods.addElement(db); } public void remove(DecBlood db) ...{ vBloods.removeElement(db); } public void clear() ...{ vBloods.removeAllElements(); }}
/** */ /** * 减血的效果 * @author ok * */ public class DecBlood ... { DecBloodManager dbm; private int x, y; private int lifeCounter; public DecBlood(DecBloodManager dbm) ...{ this.dbm = dbm; } public void setPosition(int wx, int wy) ...{ x = wx; y = wy; } public void setLifeCounter(int max) ...{ lifeCounter = max; } public void render(Graphics g, int ox, int oy) ...{ //render //update if(--lifeCounter < 0) ...{ //life over dbm.remove(this); } }}
基本思想是这样的:
在Manager里面渲染所有子节点, 而每个子节点被渲染时, 顺便更新状态; 如果子节点到了规定的时间, 就自动销毁; 也就是把自己从Manager里面移除;
但是对Vector的操作, 移除之后, 会造成Vector.size()马上减少;因此, 可能会造成错位
这时如果用++,
for(int i = 0; i < v.size(); i++);
这会造成潜在的危险;
然而如果我们用--的话, 移除一个后, 只会把这个index后面的元素往前移动, 而这些被移动的元素, 都已经是我们轮询过得了, 而前面那些不需要移动的元素, 则刚好是我们本次循环尚未check的节点;
看来, 有时候必须要用"--"啊!