Search Unity

I need help fixing my code which determines if an enemy turns left or right.

Discussion in 'Scripting' started by ToastHatter, May 28, 2017.

  1. ToastHatter

    ToastHatter

    Joined:
    Nov 11, 2016
    Posts:
    53
    I have written a piece of code which determines if the Ai should turn left or right, it does work but it cannot be constantly checking which side the transform is on as it just causes the ai to keep flipping from left and right.

    How do i adapt this piece of code so that it can constantly be checking to see which side the player is on without it breaking.

    Code (CSharp):
    1. void Update () {
    2.         Moving = true;
    3.         target = GameObject.FindWithTag ("Player").transform;
    4.         float step = maxSpeed * Time.deltaTime;
    5.         transform.position = Vector3.MoveTowards (transform.position, target.position, step);
    6.         Point = transform.InverseTransformPoint (target.position);
    7.         if (Point.x > 0) {
    8.             print("right");
    9.             if (Big == true) {
    10.                 transform.localScale = new Vector3 (2, 2, 2);
    11.             } else {
    12.                 transform.localScale = new Vector3 (1, 1, 1);
    13.             }
    14.             Right = true;
    15.         }
    16.         if (Point.x < 0) {
    17.             print ("left");
    18.             if (Big == true) {
    19.                 transform.localScale = new Vector3 (-2, 2, 2);
    20.             } else {
    21.                 transform.localScale = new Vector3 (-1, 1, 1);
    22.             }
    23.             Right = false;
    24.         }
    25.         if (Point.y > 0) {
    26.             rb2d.AddForce (Vector2.up * Jumppower);
    27.             Jump.Play ();
    28.             Grounded = false;
    29.         }
    30.