September 9, 2008

一只n00b的两个月ActionScript开发经验 (1)

ActionScript是Flash的Script语言,以下内容基于ActionScript3,即Flash CS3 +
内容基本上都是两个月过程中碰到过的林林总总的问题...如果群众们也有兴趣做做Flash小游戏的话,可能会有帮助。
  • Singleton Mode
    即单态模式,通常似乎都是Design Pattern的第一章的内容...其实就是对于那些在整个游戏进程中只有一个实例的Class,用单态模式会相当程度的简化各个组件间的互相访问...偶的Prototype里大多数的Class都是Singleton Mode
ActionScript 3语言: Singleton Mode
package {
public class Singleton{

      public static var instance:Singleton;

      public function Singleton(){
      }

      public static function getInstance():Singleton{
            if (instance == null){
                  instance = new Singleton();
                  return instance;
            }
            else
                  return instance;
      }        
}
}
  • 尽量不要用Timer类
    很多UI或者逻辑的Behavior,最直观的想法就是用Time Event来实现...但是首先Timer多了很难Manage,因为如果要有Pause Game或者有新的状态打断Timer的话就需要很多代码来维护每一个Timer...还有一个问题就是Flash的Timer不是一个精确的Timer,他的每次CallBack其实是Timer的时间+其他Function累积的时间...在极端情况下甚至一个100ms * 50次的Timer会需要10秒钟才能爬完...因此...正确的做法是只使用一个update Timer,其他的都用累积dT时间来处理...
  • 带FPS补偿的Global Update做法...
    其实就是调整每次update的Timer...会使各种逻辑上的update顺畅很多...
ActionScript 3语言: Global Update Loop
private function init(){
       updateTimer = new Timer(gameLogic.UPDATE_INTERVAL,1);   //inifinite Loop
       updateTimer.addEventListener(TimerEvent.TIMER_COMPLETE, update);
       lastUpdatedTime = getTimer();             
  }

  private function update(e:TimerEvent){
       //Update Logic
       //Blablabla
     
       //New Timer
       var currentTime:Number = getTimer();
       var newTimeInterval = gameLogic.UPDATE_INTERVAL - (currentTime - lastUpdatedTime - gameLogic.UPDATE_INTERVAL);
       lastUpdatedTime = currentTime;
       if (newTimeInterval <= 0)
             newTimeInterval = 5;
       updateTimer = new Timer(newTimeInterval,1);    //inifinite Loop
       updateTimer.start();
       updateTimer.addEventListener(TimerEvent.TIMER_COMPLETE, update);
}
待续...

No comments: