To actually display a 3D object on the screen, we will need to create another class called SphereDemo
. Let's take a look at the code for the SphereDemo
class.
package {
Away3D includes a number of primitive shapes that can be easily added to the scene. These primitives are covered in more detail in Chapter 2, Creating and Displaying Primitives. We will be adding the sphere primitive to the scene, which is represented by the Sphere
class.
import away3d.primitives.Sphere;
The SphereDemo
class will extend Away3DTemplate
, allowing us to initialize and update the Away3D engine with a minimum amount of code.
public class SphereDemo extends Away3DTemplate {
In the SphereDemo
constructor, we simply call the Away3DTemplate
constructor with the super()
statement, which will in turn initialize the Away3D engine by calling the initUI()
, initEngine()
, initScene()
, and initListeners()
functions.
public function SphereDemo() { super(); }
The
initScene()
function was deliberately left empty in the Away3DTemplate
class. The SphereDemo
class overrides this function to add a sphere to the scene.
protected override function initScene():void {
First, we call the initScene()
function from the base class.
In truth, calling the initScene()
function from the base class will do nothing, as this function was deliberately left empty in the Away3DTemplate
class. However, calling the base class functions is a good habit to get into, as it is required by other functions like initEngine()
and initListeners()
.
super.initScene();
We then create a new Sphere
3D object. The Sphere
3D object will be placed at the origin of the scene, by default. If you remember from the Away3DTemplate
class, the camera is placed at (0, 0, -1000), and is oriented to look back at the scene origin. This means the Sphere
3D object will be in front of the camera when we run the application.
A number of Away3D classes accept an instance of the Object
class, called an init object, as a constructor parameter. This init object is created using object literal notation. The following code would create a Sphere
object, and place it at (0, 0, 500).
var sphere:Sphere = new Sphere(
{
x: 0,
y: 0,
z: 500
}
);
Object literal notation is a short-hand way of creating associative arrays, which are instances of the Object
class that maps properties to values. The following code has the same effect as the previous code:
var obj:Object = new Object();
obj.x = 0;
obj.y = 0;
obj.z = 500;
sphere = new Sphere(obj);
The properties of the Sphere
object could also have been set after it was instantiated.
var sphere:Sphere = new Sphere();
sphere.x = 0;
sphere.y = 0;
sphere.z = 500;
Although we don't use an init object here, they will be used extensively throughout the rest of the book.
var sphere:Sphere = new Sphere ();
Finally, in order for the sphere to be visible it needs to be added as a child of the scene.
scene.addChild(sphere); } } }