17 July 2011

AS3: Wave of values class function - produces incremental and decremental values

Sometimes it's necessary to have a value increment until it gets to a certain point and then have it decrement again in a wave shape. A simple Math.sin() calculation will work in some cases but its not easy to control the increment using that method. This handy & simple class makes it quick and easy to do just this. There's lots of room for improvements & additions so feel free to post updates :)


Please see right hand pane before copying my code- thanks! >

package com.cron {
 
 public class valueWave {
  private var inc,startno,counter,max,min //counter is always>0
  public var num //latest value
  
  public function valueWave($min:Number=0, $max:Number=10, $increment:Number=1, $startno:Number=0 ) {
   if($max<$min){
    trace("valueWave ERROR: max must be greater than min")
    return
   }
   inc=$increment
   startno=$startno
   counter=$startno
   num=$startno
   max=$max
   min=$min
  }
  
  public function next(){
   if(max==0){return(num);} //disable if max and min are the same
   num = Math.abs((counter % (2*(max-min))) - (max-min)) + min;
   counter += inc;
   return(num)
  }
  
  public function reset(){
   counter=startno
  }
  
 }
 
}

//USAGE::
//the code above should be saved as [your root class path]/com/cron/valueWave.as
import com.cron.valueWave

var W=new valueWave(1,10,1,5);

addEventListener(Event.ENTER_FRAME,function(){
    trace(W.next());
})

//OUTPUTS:
5,4,3,2,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,etc

No comments:

Post a Comment

Cron Design Studio: Dublin based web design & software development