Skip to content

C3D 06 Applying Forces

robsilv edited this page Apr 12, 2013 · 13 revisions

As per the 2D equivalent, this tutorial builds on the last by introducing a torque Behaviour.

Applying Forces screenshot

Create the following class:

package components.behaviours
{
	import cadet.core.Component;
	import cadet.core.ISteppableComponent;
	
	import cadet3DPhysics.components.behaviours.RigidBodyBehaviour;
	
	import flash.geom.Vector3D;
	
	public class ApplyTorqueBehaviour extends Component implements ISteppableComponent
	{
		public var rigidBodyBehaviour			:RigidBodyBehaviour;
		public var torque				:Number;
		public var targetVelocity			:Vector3D;
		
		public function ApplyTorqueBehaviour( torque:Number = 50, targetVelocity:Vector3D = null )
		{
			this.torque = torque;
			
			if ( !targetVelocity ) {
				targetVelocity = new Vector3D(2,0,0);
			}
			
			this.targetVelocity = targetVelocity;
		}
		
		override protected function addedToParent():void
		{
			addSiblingReference( RigidBodyBehaviour, "rigidBodyBehaviour" );
		}
		
		public function step(dt:Number):void
		{
			// If we're not attached to an Entity with a RigidBodyBehaviour, then skip.
			if ( !rigidBodyBehaviour ) return;
			
			var angularVelocity:Vector3D = rigidBodyBehaviour.getAngularVelocity();
			
			if (!angularVelocity) return;
			
			// Calculate a ratio where 0.5 means we're spinning at half the target speed, and 1 means full speed.
			var ratio:Number = angularVelocity.x / targetVelocity.x;
			
			// Scale the torque value by the opposite of the ratio, so as we near the target
			// velocity, we reduce the amount of torque applied.
			rigidBodyBehaviour.applyTorque(new Vector3D((1-ratio)*torque));
		}
	}
}

Compare the Behaviour above to its 2D equivalent. Note that the implementation is almost identical, save the fact that -as we are now in 3D- we've replaced a few references to Numbers with references to Vector3Ds.

Add the following code to your app's constructor, beneath the part where you create all of the other cubes.

// Add big cube Material
var bigCubeMaterial:ColorMaterialComponent = new ColorMaterialComponent();
bigCubeMaterial.color = 0xFF0000;
cadetScene.children.addItem(bigCubeMaterial);
// Add big cube
var bigCube:MeshComponent  = addCubeEntity( 0, 6500, 0, 200, 200, 200 );
bigCube.materialComponent = bigCubeMaterial;
bigCube.children.addItem(new ApplyTorqueBehaviour());

Here we're simply adding a single bigger cube and giving it a red material so it stands out, then adding the ApplyTorqueBehaviour as a child of the bigCube Component.

Build and run to watch the red cube traverse the screen in a similar manner to the rotatingRectangle in the equivalent 2D tutorial.

< Previous