Game Development Reference
function Update ()
direction = target.transform.position — transform.
if(direction.magnitude > 60)
state = "ATTACK";
else if (direction.magnitude < 10)
state = "RETREAT";
//act on state
if(state == "ATTACK")
//look at and move toward planet
this.transform.Translate(Vector3.forward * 0.3);
else if (state == "RETREAT")
//look at and move toward homebase
Vector3.forward * 0.3);
Step 8. Save and play. The rocket will move back and forth between
the planet and its starting location. This is achieved by creating a new
variable called state that stores the rocket's current objective or goal.
This is a very simple version of a finite state machine used commonly in
games for controlling AI. If the rocket is further than 60 away from the
planet it will go into attack mode. If it gets closer than 10 it will retreat.
Step 9. So far we've created a rather unnaturally moving rocket ship.
It will look better if it curves to turn rather than simply flipping on the
spot. To achieve this, modify your code to that in Listing 2.5 .
Listing 2.5 Adding a Slerp to the Movement for Smooth Turning
private var target: GameObject;
private var direction:Vector3;
private var state = "ATTACK";
private var rotationSpeed = 4.0;