ActionScript 3 Papervision基础模板

/**
* ...
* @author Luke Mitchell
* @version 1.8.0
*/

package  {
	// These lines make different 'pieces' available in your code.
	import flash.display.Sprite; // To extend this class
	import flash.events.Event; // To work out when a frame is entered.
	import org.papervision3d.core.proto.CameraObject3D;
	
	import org.papervision3d.view.Viewport3D; // We need a viewport
	import org.papervision3d.cameras.*; // Import all types of camera
	import org.papervision3d.scenes.Scene3D; // We'll need at least one scene
	import org.papervision3d.render.BasicRenderEngine; // And we need a renderer
	
	public class PaperBase extends Sprite { //Must be "extends Sprite"
		
		public var viewport:Viewport3D; // The Viewport
		public var renderer:BasicRenderEngine; // Rendering engine
		
		public var current_scene:Scene3D;
		public var current_camera:CameraObject3D;
		public var current_viewport:Viewport3D;
		// -- Scenes -- //
		public var default_scene:Scene3D; // A Scene
		// -- Cameras --//
		public var default_camera:Camera3D; // A Camera
		
		public function init(vpWidth:Number = 800, vpHeight:Number = 600):void {
			initPapervision(vpWidth, vpHeight); // Initialise papervision
			init3d(); // Initialise the 3d stuff..
			init2d(); // Initialise the interface..
			initEvents(); // Set up any event listeners..
		}
		
		protected function initPapervision(vpWidth:Number, vpHeight:Number):void {
			// Here is where we initialise everything we need to
			// render a papervision scene.
			if (vpWidth == 0) {
				viewport = new Viewport3D(stage.width, stage.height, true, true);
			}else{
				viewport = new Viewport3D(vpWidth, vpHeight, false, true);
			}
			// The viewport is the object added to the flash scene.
			// You 'look at' the papervision scene through the viewport
			// window, which is placed on the flash stage.
			addChild(viewport); // Add the viewport to the stage.
			// Initialise the rendering engine.
			renderer = new BasicRenderEngine();
			// -- Initialise the Scenes -- //
			default_scene = new Scene3D();
			// -- Initialise the Cameras -- //
			default_camera = new Camera3D();
			
			current_camera = default_camera;
			current_scene = default_scene;
			current_viewport = viewport;
			
		}
		
		protected function init3d():void {
			// This function should hold all of the stages needed
			// to initialise everything used for papervision.
			// Models, materials, cameras etc.
		}
		
		protected function init2d():void {
			// This function should create all of the 2d items
			// that will be overlayed on your papervision project.
			// User interfaces, Heads up displays etc.
		}
		
		protected function initEvents():void {
			// This function makes the onFrame function get called for
			// every frame.
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			// This line of code makes the onEnterFrame function get
			// called when every frame is entered.
		}
		
		protected function processFrame():void {
			// Process any movement or animation here.
		}
		
		protected function onEnterFrame( ThisEvent:Event ):void {
			//We need to render the scene and update anything here.
			processFrame();
			renderer.renderScene(current_scene, current_camera, current_viewport);
		}
		
	}
	
}

ActionScript 3 Papervision3D - Pixel Perfect Planes

3dOBJECT.z = (camera.zoom * camera.focus) - Math.abs(camera.z)

ActionScript 3 AS3在阵列上使用Push,Pop,Unshift和Shift

var myArray:Array = new Array();


// PUSH
// Adds one or more elements to the end of an array and returns the new length of the array.
myArray = ["a","b","c","d"];
trace(myArray);
myArray.push("e");
trace(myArray);
// OUTPUT
// a,b,c,d
// a,b,c,d,e


// POP
// Removes the last element from an array and returns the value of that element.
myArray = ["a","b","c","d"];
trace(myArray);
myArray.pop();
trace(myArray);
// OUTPUT
// a,b,c,d
// a,b,c


// UNSHIFT
// Adds one or more elements to the beginning of an array and returns the new
// length of the array. The other elements in the array are moved from their 
// original position, i, to i+1.
myArray = ["a","b","c","d"];
trace(myArray);
myArray.unshift("_");
trace(myArray);
// OUTPUT
// a,b,c,d
// _,a,b,c,d



// SHIFT
// Removes the first element from an array and returns that element.
// The remaining array elements are moved from their original position, i, to i-1.
myArray = ["a","b","c","d"];
trace(myArray);
myArray.shift();
trace(myArray);
// OUTPUT
// a,b,c,d
// b,c,d

ActionScript 3 AS3加载SWF文件跨域

// Please read the full blog post from Big Spacehip to understand the issue.
// http://www.bigspaceship.com/blog/labs/flash-files-domains-and-security-errors-oh-my/

var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, _onLoadComplete_handler);
if(Security.sandboxType == Security.REMOTE){
	var context:LoaderContext = new LoaderContext();
	context.securityDomain = SecurityDomain.currentDomain;
	l.load(new URLRequest('http://domain.com/extFile.swf'), context);
}else{
	l.load(new URLRequest('extFile.swf'));
}

ActionScript 3 使用GreenSock LoaderMax进行简单Flash / AS3幻灯片放映

//Get the LoaderMax and GreenSock classes at http://www.greensock.com/

import com.greensock.*;
import com.greensock.loading.*;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.display.*;

var xml:XMLLoader;
var images;
var current = 0;
var previous;

function init(){
	LoaderMax.activate([ImageLoader]);
	xml = new XMLLoader("images.xml", {name:"images", onComplete:onXmlLoaded});
	xml.load();
}

function onXmlLoaded(e){
	images = LoaderMax.getContent("images");
	nextImage();
	
}

function nextImage(){

	TweenLite.from(images[current],1,{alpha:0,
		onStart:function(){
			addChild(images[current]);
		},
		onComplete:function(){
			if(previous){
				removeChild(images[previous])
			}
			previous = current;
			if(current<images.length-1){
				current++;
			}else{
				current=0;
			}
			setTimeout(nextImage,2000);
		}
	});
}


init();

ActionScript 3 As3:多点触控缩放和旋转

package
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.TransformGestureEvent;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Multitouch;
	import flash.ui.MultitouchInputMode;
	
	[SWF(width=320, height=460, frameRate=24, backgroundColor=0x000000)]
	public class GestureExample extends Sprite
	{
		[Embed(source="african_elephant.jpg")]
		public var ElephantImage:Class;
		public var scaleDebug:TextField;
		public var rotateDebug:TextField;

		public function GestureExample()
		{
			// Debug
			var tf:TextFormat = new TextFormat();
			tf.color = 0xffffff;
			tf.font = "Helvetica";
			tf.size = 11;
			this.scaleDebug = new TextField();
			this.scaleDebug.width = 310;
			this.scaleDebug.defaultTextFormat = tf;
			this.scaleDebug.x = 2;
			this.scaleDebug.y = 2;
			this.stage.addChild(this.scaleDebug);
			this.rotateDebug = new TextField();
			this.rotateDebug.width = 310;
			this.rotateDebug.defaultTextFormat = tf;
			this.rotateDebug.x = 2;
			this.rotateDebug.y = 15;
			this.stage.addChild(this.rotateDebug);

			var elephantBitmap:Bitmap = new ElephantImage();
			var elephant:Sprite = new Sprite();
			
			elephant.addChild(elephantBitmap);
			
			elephant.x = 160;
			elephant.y = 230;
			
			elephantBitmap.x = (300 - (elephantBitmap.bitmapData.width / 2)) * -1;
			elephantBitmap.y = (400 - (elephantBitmap.bitmapData.height / 2)) *-1;
			
			this.addChild(elephant);

			Multitouch.inputMode = MultitouchInputMode.GESTURE;
			elephant.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
			elephant.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);
		}
		
		private function onZoom(e:TransformGestureEvent):void
		{
			this.scaleDebug.text = (e.scaleX + ", " + e.scaleY);
			var elephant:Sprite = e.target as Sprite;
			elephant.scaleX *= e.scaleX;
			elephant.scaleY *= e.scaleY;
		}
		
		private function onRotate(e:TransformGestureEvent):void
		{
			var elephant:Sprite = e.target as Sprite;
			this.rotateDebug.text = String(e.rotation);
			elephant.rotation += e.rotation;
		}
	}
}

ActionScript 3 创建Flash SharedObject(Flash Cookie)

//create SO
var mySharedObject:SharedObject = SharedObject.getLocal("republicofcode");
mySharedObject.data.firstName = "John";
mySharedObject.data.lastName = "Doe";
mySharedObject.flush();

//Read SO
var mySharedObject:SharedObject = SharedObject.getLocal("republicofcode");
trace(mySharedObject.data.firstName);
trace(mySharedObject.data.lastName);


//Delete SO
var mySharedObject:SharedObject = SharedObject.getLocal("republicofcode");
mySharedObject.clear();


//example for SO where it stored a X & Y coordinates of a movie
////////////////////////////////////////////////////////////////


var mySO:SharedObject = SharedObject.getLocal("republicofcode");

movie_mc.x = mySO.data.my_x;
movie_mc.y = mySO.data.my_y;

if (!mySO.data.my_y) {
movie_mc.x = 150;
movie_mc.y = 100;
}

movie_mc.addEventListener (MouseEvent.MOUSE_DOWN, onDown);
function onDown (e:MouseEvent):void {
var my_mc = e.target;
my_mc.startDrag ();
}

movie.addEventListener (MouseEvent.MOUSE_UP, onUP);
function onUP (e:MouseEvent):void {
logo_mc.stopDrag ();
mySO.data.my_x = movie_mc.x;
mySO.data.my_y = movie_mc.y;
mySO.flush ();
}

movie_mc.buttonMode=true;

ActionScript 3 时间戳的相对时间

//###############################
//Usage:
var myRelativeTime:String = timestampToRelative("Sun Oct 24 20:07:33 +0000 2010");
//returns a string
//###############################

function timestampToRelative(timestamp:String):String {
	//--Parse the timestamp as a Date object--\\
	var pastDate:Date = new Date(timestamp);
	//--Get the current data in the same format--\\
	var currentDate:Date = new Date();
	//--seconds inbetween the current date and the past date--\\
	var secondDiff:Number = (currentDate.getTime() - pastDate.getTime())/1000;

	//--Return the relative equavalent time--\\
	switch (true) {
		case secondDiff < 60 :
			return int(secondDiff) + ' seconds ago';
			break;
		case secondDiff < 120 :
			return 'About a minute ago';
			break;
		case secondDiff < 3600 :
			return int(secondDiff / 60) + ' minutes ago';
			break;
		case secondDiff < 7200 :
			return 'About an hour ago';
			break;
		case secondDiff < 86400 :
			return 'About ' + int(secondDiff / 3600) + ' hours ago';
			break;
		case secondDiff < 172800 :
			return 'Yesterday';
			break;
		default :
			return int(secondDiff / 86400) + ' days ago';
			break;
	}
}

ActionScript 3 AS3随机化数组

function fRandomize(vArray : Array) : void
{
	var i : int;
	var j : int;

	for (i = 0; i < vArray.length - 1; i++)
	{
		j = i + Math.floor(Math.random() * (vArray.length - i));
		if (j != i)
			fSwap(vArray, i, j);
	}
}

function fSwap(vArray : Array, i : uint, j : uint) : void
{
	var t : *;

	t = vArray[i];
	vArray[i] = vArray[j];
	vArray[j] = t;
}

ActionScript 3 使用AS3读取不同的文件类型

import flash.filesystem.FileMode;
      import flash.filesystem.FileStream;
      import flash.filesystem.File;
       
      var myFile:File = File.appResourceDirectory; // Create out file object and tell our File Object where to look for the file
      myFile = myFile.resolve("mySampleFile.txt"); // Point it to an actual file
       
      var fileStream:FileStream = new FileStream(); // Create our file stream
      fileStream.open(myFile, FileMode.READ);
       
      var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); // Read the contens of the 
      fileContents_txt.text = fileContents; // Display the contents. I've created a TextArea on the stage for display
       
      fileStream.close(); // Clean up and close the file stream