Hey, I am working on something where I have a flying craft in a circular track that is bounded by walls left and right all the way around the track. I want to have an Autopilot mode where it will fly around the track. I thought of doing this with raycasts and setting limitations.
Here is the code so far:
private var distanceToGround;
private var distanceUp;
private var distanceLeft;
private var distanceRight;
private var distanceForward;
private var forwardNormal;
function Update()
{
// always mvoe forward
this.rigidbody.AddRelativeForce(Vector3(0, 0, 200));
// down
var hit : RaycastHit;
if (Physics.Raycast (this.transform.position, -Vector3.up, hit, 100.0)) {
distanceToGround = hit.distance;
}
if (distanceToGround < 5.0)
{
this.transform.position.y = Mathf.Lerp(this.transform.position.y, this.transform.position.y + (4.0 - distanceToGround), Time.time);
}
// up
if (Physics.Raycast (this.transform.position, -Vector3.up, hit, 100.0)) {
distanceUp = hit.distance;
}
if (distanceUp > 20.0)
{
this.transform.position.y = Mathf.Lerp(this.transform.position.y, this.transform.position.y + (12.0 - distanceToGround), Time.time);
}
// forward for turning
if (Physics.Raycast (this.transform.position, -Vector3.up, hit, 100.0)) {
distanceForward = hit.distance;
forwardNormal = hit.normal;
}
Debug.Log(distanceForward);
if (distanceForward <= 25)
{
var checkVector : Vector3 = transform.InverseTransformDirection(forwardNormal);
if (checkVector.x > 0)
{
transform.Rotate(0, Time.deltaTime * 30, 0);
}
else
{
transform.Rotate(0, -Time.deltaTime * 30, 0);
}
}
}
Right now its movement is kinda working. I always tell the craft to go forward on its local axis. When it gets to the wall whether it be left or right i need it to turn. I dont know if the code is right. Its based off of what Marty did in another thread. Sometimes the craft just goes in circles. Other times it works, and sometimes the craft skips hops jumps and then goes bonkers. Any suggestions is appreciated!