Download the starting code for this lab from this link and unzip the files. Import the project into Titanium Studio. Update the tiapp.xml, if necessary (e.g. to set an appropriate SDK version or build target for your environment).
First we will create and initialize the animator and its behaviors. Use The Ti.UI.iOS.createAnimator() function to do this. Set the animator's reference view to animatorReferenceView from the index view file.
Now create the GravityBehavior behavior for the animator. Initialize it with an x value of 0.0 and a y value of 1.0.
Create a CollisionBehavior and initialize it with treatReferenceAsBoundary set to true.
- Create a DynamicItemBehavior and initialize it with friction of 10 and elasticity of 0.5.
- Add the gravity behavior, collision behavior and the dynamic item behavior to the animator with the addBehavior method.
- We now want to add behaviors to the views we want to be able to interact with.
- The gravityView should be added to gravity behavior, collision behavior and dynamic item behavior.
- The collisionView should be added to the collision behavior and the dynamic item behavior. This view will float around the screen and not be affected by gravity.
- In the function onItemClick(), use the _dynamicItemBehavior to add angular velocity of 80 to the source that fired the event.
- For the directional button functions, we want to change the _gravityBehavior to match the gravity to the direction that was selected. In each function, determine which direction the gravity should pull, and set the gravity direction accordingly.
- Run your app and test that the directional arrows cause the red box to fall to that side of the screen, and tapping a box causes it to "jump".
You can download the completed application from: this link.