-
Notifications
You must be signed in to change notification settings - Fork 21
C3D 04 Writing your own Behaviour
As with the previous tutorial, this tutorial should seem very similar to its 2D equivalent.
Create the following class:
package components.behaviours
{
import cadet.core.Component;
import cadet.core.ISteppableComponent;
import cadet3D.components.core.MeshComponent;
public class AnimateRotationBehaviour extends Component implements ISteppableComponent
{
public var mesh :MeshComponent;
public var rotationSpeed :Number = 30;
public function AnimateRotationBehaviour()
{
super();
}
override protected function addedToParent():void
{
if ( parentComponent is MeshComponent ) {
mesh = MeshComponent(parentComponent);
}
}
public function step( dt:Number ):void
{
if ( !mesh ) return;
mesh.rotationX += rotationSpeed * dt;
}
}
}
Note how similar this code is to the behaviour in the 2D example. The main difference is that it stores a reference to a MeshComponent
rather than a Transform2D
. Also note that the code in addedToParent()
doesn't use addSiblingReference()
as per the 2D example, as in this instance, the 3D transform is implicitly part of the parent MeshComponent
.
Add the following code below your cubeEntity
in the app's constructor:
var animateRotationBehaviour:AnimateRotationBehaviour = new AnimateRotationBehaviour();
cubeEntity.children.addItem(animateRotationBehaviour);
Note that the previously mentioned addedToParent()
code takes care of associating the MeshComponent
with the AnimateRotationBehaviour
when the Behaviour is added as a child of the MeshComponent
. If we wanted to add the AnimateRotationBehaviour
as a child of the CadetScene
instead of adding it to the cubeEntity
, we'd need to explicitly associate the two like so:
cadetScene.children.addItem(animateRotationBehaviour);
animateRotationBehaviour.mesh = cubeEntity;
Build and run to see the cube rotate..!