Monday, August 3, 2009

Getting started with Away3D

Today, I decided to play with Away3D and immediately found it to be much better than Papervision. Comparatively, Away3D is much faster than Papervision ( implementation of FP10 features ). So, here is a simple tutorial to get you up and going with Away3D.
In this tutorial, I'll be using Flex Builder to create an ActionScript project. I'm naming it Away3DTest. Now download the latest Away3D build from here. Extract the source to the src folder and type in the following code :


package
{
import away3d.cameras.Camera3D;
import away3d.containers.Scene3D;
import away3d.containers.View3D;
import away3d.core.math.Number3D;
import away3d.core.render.Renderer;
import away3d.materials.BitmapMaterial;
import away3d.primitives.Cube;

import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;

[SWF( backgroundColor = '0x000000')]
public class Away3DTest extends Sprite
{
[Embed(source='texture.jpg')]
private var Texture:Class;

private var scene:Scene3D;
private var camera:Camera3D;
private var view:View3D;

private var cube:Cube;

public function Away3DTest()
{
initAway3D();
initObjects();
}

private function initAway3D():void
{
camera = new Camera3D();
camera.x = 100;
camera.y = 100;
camera.z = -1000;
camera.lookAt( new Number3D() );

scene = new Scene3D();

view = new View3D();
view.x = 200;
view.y = 200;
view.scene = scene;
view.camera = camera;
view.renderer = Renderer.BASIC;
addChild(view);
}

private function initObjects():void
{
cube = new Cube();
cube.material = new BitmapMaterial(Bitmap(new Texture()).bitmapData);
scene.addChild(cube);

addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(e:Event):void
{
cube.rotationX += 1;
cube.rotationY += 1;
cube.rotationZ += 1;

view.render();
}

}
}



Here I assume you have a file named texture.jpg in your source directory.Now an explanation of the code :
  1. We create variables for the View3D, Camera3D and the Scene3D class and assign the scene and the camera variable to the view variable. This is setting up the Away3D engine and is written as a seperate function initAway3D()
  2. We create a cube and create a new BitmapMaterial for it using the embedded texture.
  3. We create an ENTER_FRAME event listener which does the rendering using the view.render() method. Meanwhile we'll also rotate the cube on all 3 axes.
  4. Save and run you should get a cube with the texture rotating on all the axes.
Hope that was useful to anyone starting Away3D. Happy coding. :D

No comments:

Post a Comment