Search Unity

How to set boundaries in enemy 2D movement?

Discussion in 'Scripting' started by Pixitales, Jul 5, 2019.

  1. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    177
    I adapted this code a little from gamesplus james tutorial. I got it a little bit working. I want the enemy to change direction if it hits a wall. In this case, I am using if transform.position.y > some number.... because I dont want my enemy to detect wall collision. It kinda works but I think waiting for timeBetweenMoveCounter to reach zero everytime, it misses the timing to change direction. I also don't want it to read the code reverse direction like 100 times per second. This runs from void update. How do I arrange this?



    Code (CSharp):
    1.  
    2.     private float timeBetweenMove = 1;
    3.     private float timeBetweenMoveCounter;
    4.     private float timeToMove = 2;
    5.     private float timeToMoveCounter;
    6.  
    7.     public void RandomMovement()
    8.     {
    9.         if (IsAlive)
    10.         {
    11.             if (isPatrolling)
    12.             {
    13.                 timeToMoveCounter -= Time.deltaTime;
    14.                 MyRigidbody.velocity = Direction;
    15.  
    16.                 if (timeToMoveCounter < 0f)
    17.                 {
    18.                     isPatrolling = false;
    19.                     timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
    20.                 }
    21.             }
    22.             else
    23.             {
    24.                 timeBetweenMoveCounter -= Time.deltaTime;
    25.                 MyRigidbody.velocity = Vector2.zero;
    26.  
    27.                 if (timeBetweenMoveCounter < 0f)
    28.                 {
    29.                     isPatrolling = true;
    30.                     timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeBetweenMove * 1.25f);
    31.  
    32.                     Direction = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f) * MoveSpeed).normalized;
    33.  
    34.                     if (transform.position.y > 6.5f)
    35.                     {
    36.                         Debug.Log("max y");
    37.                         Direction = new Vector2(0f, -2f);
    38.                     }
    39.                     else if (transform.position.y < -10)
    40.                     {
    41.                         Debug.Log("mix y");
    42.                     }
    43.                 }
    44.             }
    45.         }
    46.     }
     
    Last edited: Jul 5, 2019
  2. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    177
    Its really actually easy to solve but i just wanna see your ideas how you would set this up. You dont really need to have advance knowledge of c#
     
unityunity