Hey guys,
this is the code I am having trouble with…
I am trying to build a TD game in which, as usual, multiple enemies of the same kind spawn and make their way to the finish line. I am trying to make one enemy go left, the next one right and then oscillate between the two, but instead once they all go into the same direction and they start to rapidly oscillate right at the exit going left, right, left, right etc…
Now, how would I go about this the correct way? because this is clearly not working…
public class Enemy_Movement_Normal_Speed : MonoBehaviour
{
public float moveSpeed = 2f;
public bool changeDir1;
public bool changeDirleft;
public Transform changeDir2;
public int changeDirectionDir1 = 1;
void FixedUpdate()
{
Vector3 vel = transform.forward * moveSpeed; //move forward
vel.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = vel;
if (changeDir1 == true && changeDirectionDir1 == 1) //move right at the junction
{
Vector3 vel2 = transform.right * moveSpeed;
vel2.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = vel2;
//transform.LookAt(changeDir2)
Debug.Log(changeDirectionDir1);
}
if (changeDir1 == true && changeDirectionDir1 == 2) //move left at the junction
{
Vector3 vel2 = -transform.right * moveSpeed;
vel2.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = vel2;
//transform.LookAt(changeDir2)
Debug.Log(changeDirectionDir1);
}
if (changeDirleft == true) //move foward at different junction again,
//called left because it
//is like actually moving left, in game
//world however it's forward
{
Vector3 vel2 = transform.forward * moveSpeed;
vel2.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = vel2;
}
}
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Change Dir 1")) //is the enemy at the first junction?
{
changeDir1 = true;
changeDirectionDir1 += 1; //this is supposed to go up once when they enter
// the trigger in order for the next one to move left
Debug.Log("Entered the first trigger");
}
if (other.CompareTag("Change Dir Left"))
{
changeDir1 = false;
changeDirleft = true;
Debug.Log("Entered the second trigger");
}
}
public void OnTriggerExit(Collider other)
{
if (other.CompareTag("Change Dir 1"))
{
changeDirectionDir1 -= 1; //subtract one again so that
//once one has left the junction the next one goes right again
}
}
}
Sorry for the messy code, I am still a beginner ^^