Game Development Reference
In-Depth Information
Listing 2.3 Moving an Object by a Small Amount Each Update
private var target: GameObject;
private var direction:Vector3;
function Start ()
{
target = GameObject.Find("Base");
}
function Update ()
{
this.transform.LookAt(target.transform.position);
this.transform.Translate(Vector3.forward * 0.3);
}
Step 5. To make the rocket ship move toward the planet, modify the
code to that listed in Listing 2.3 .
Step 6. Save and play. The rocket ship will move toward the planet.
However, when it gets to the planet it will stop moving and start
flipping back and forth. Why? Each update, the rocket looks at the
base and moves toward it. When it is on top of the base it looks at it
and then moves forward. This moves it slightly away. The next update
it flips around to look at the base again and moves a little toward it.
infinitum.
Step 7. To make the rocket move away from the planet when it
gets too close, we can test for the distance the rocket is from the
planet and turn it back toward its starting position when it comes
within a specific distance. To do this, modify your script to that in
Listing 2.4 .
Listing 2.4 Script to Make an Object Attack and Retreat from
Another Object Based on the Distance between Them
private var target: GameObject;
private var direction:Vector3;
private var state = "ATTACK";
private var startingPosition:Vector3;
function Start ()
{
target = GameObject.Find("Base");
startingPosition = this.transform.position;
}
Search Nedrilad ::




Custom Search