- Home /
Script is Flipping Out!
Hey everyone in the script I tried making my ai ship turn while a variable is greater than zero but it never stops and spins way faster that if it was not in this while statement. Can someone take a look at how this part of the script is rotating the ship and show me how to make it rotate for a set time like I want. Please don't just throw documentation at me I already looked at it… thats how I came up with this is all that documentation.
void Avoid()
{
if(dist < 20)
{
followTarget = false;
StartCoroutine (turn());
}
}
IEnumerator turn()
{
if(followTarget == false)
{
//wait the cooldown time in a loop
float turningTime = 5f;
while (turningTime > 0)
{
transform.Rotate(0, turnSpeed * Time.deltaTime, 0 * Time.deltaTime, Space.World); //and then turn the plane
//decrement turningTime
turningTime -= Time.deltaTime;
//let unity free until next frame
yield return null;
}
}
}
Well those are kind of ok but this is really driving me crazy now… I am trying to make a ship ai that the enemy follows me if distance is something which I have done. But then I need it to circle around me if the distance gets to a certain point that way it can't run into me… then I need to make it think about in some way running from me under a certain circumstance. This is a 3d space style game...
Answer by sath · Jan 01, 2014 at 09:03 PM
//set the variable
float turningTime;
make the Avoid like this
void Avoid(){
if((dist < 20)&&(followTarget)){
followTarget = false;
turningTime = 5f;
}
}
and finally put this in Update
void Update(){
turningTime -= Time.deltaTime;
if((!followTarget)&&(turningTime>0f)){
transform.Rotate(0, turnSpeed * Time.deltaTime, 0 * Time.deltaTime, Space.World);
}
}
Answer by tanoshimi · Jan 01, 2014 at 08:26 PM
Are you calling Avoid() from your Update() loop by any chance? If so, it's probably calling turn() in every frame in which dist is less than 20, and you've stacked multiple coroutines to rotate the object, each of which last for 5 seconds.
Try adding a Boolean variable to indicate whether turn() is already running (set it to true/false at each end of the coroutine), and only call it from Avoid() if not already running.