Game Development Reference
In-Depth Information
Set the location, and find the gameObjects in an Awake function:
6.
void Awake () {
startLocation = transform.localPosition; // store the starting location
zRotation = transform.localEulerAngles.z;
stork = GameObject.Find("Stork Group"); // locate the parent object
bundle = GameObject.Find("Bundle"); // locate the parent object
}
The Baby ZB is put into the Stork Group in the Hierarchy view, but once the game starts, you will
transfer it to the Bundle. This way it will be able to retain its starting location through all of the
re-parenting.
Add the following to the Start function:
7.
transform.parent = bundle.transform; // move the baby zb into the bundle group
You will be calling a little function from the Bundle when it hits the ground to set the Baby ZBs
in motion.
8.
Add the following function:
public void Escape() {
// unparent the object
transform.parent = null;
//turn on the physics!
rigidbody2D.isKinematic = false;
// add some spin
rigidbody2D.AddTorque(-50f.50f); // on the z, the only option for 2D torque
// bounce the bun up with a random x force and random y force
rigidbody2D.AddForce(new Vector2(Random.Range(-100f,100f),Random.Range(-200f,700f)));
// start the coroutine that will manage the reset
StartCoroutine(Deactivator());
}
In this function, you unparent the Baby ZB just before turning the physics back on. Then you add
some torque to send it spinning. In Physics 2D, you can only spin a sprite relative to the screen, on
its z axis. Next you send it off with some force within a small range of its x and y directions. Finally,
you call the coroutine that will take care of resetting the Baby ZB at the end of its routine.
The Deactivator function is a bit different than the one on the bundle in that it also manages the
results of the physics forces and torques.
Create the Deactivator function:
9.
IEnumerator Deactivator () {
yield return new WaitForSeconds(Random.Range (4f,5f)); // wait 4 to 5 seconds
// turn off the physics
rigidbody2D.isKinematic = true;
rigidbody2D.velocity = Vector2.zero; // clear the velocity
rigidbody2D.angularVelocity = 0; // clear the spin velocity
Search WWH ::




Custom Search