Search Unity

Random Movement Script

Discussion in 'Scripting' started by Dlightb, Jul 1, 2021.

  1. Dlightb

    Dlightb

    Joined:
    Mar 9, 2021
    Posts:
    3
    I'm a little new to Unity and I've been following tutorials on how to make NPCs move. I have a script that allows an NPC to move randomly, it will choose a new direction to move in after a random time period. How do I make it so that I can set up a collider and they also choose a new direction when they contact the collider. I tried to add it through OnCollisionEnter2d but I must be doing it wrong.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class NPCMovement : MonoBehaviour
    6. {
    7.     internal Transform thisTransform;
    8.     public Animator anim;
    9.     public float moveSpeed = 2f;
    10.     public Vector2 decisionTime = new Vector2(1, 4);
    11.     internal float decisionTimeCount;
    12.     private Rigidbody2D rb;
    13.     public Collider2D bound;
    14.    
    15.  
    16.     internal Vector3[] moveDirections = new Vector3[] { Vector3.right, Vector3.left, Vector3.up, Vector3.down, Vector3.zero, Vector3.zero };
    17.     internal int currentMoveDiretion;
    18.     // Start is called before the first frame update
    19.     void Start()
    20.     {
    21.         thisTransform = this.transform;
    22.         decisionTimeCount = Random.Range(decisionTime.x, decisionTime.y);
    23.  
    24.         rb = GetComponent<Rigidbody2D>();
    25.         ChooseMoveDirection();
    26.     }
    27.  
    28.     // Update is called once per frame
    29.     void Update()
    30.     {
    31.         Vector3 direction = moveDirections[currentMoveDiretion];
    32.         float xDir = direction.x;
    33.         float yDir = direction.y;
    34.  
    35.         thisTransform.position += direction * Time.deltaTime * moveSpeed;
    36.  
    37.         if (anim)
    38.         {
    39.             anim.SetFloat("MoveX", xDir);
    40.             anim.SetFloat("MoveY", yDir);
    41.         }
    42.         if (decisionTimeCount > 0) decisionTimeCount -= Time.deltaTime;
    43.         else
    44.         {
    45.             decisionTimeCount = Random.Range(decisionTime.x, decisionTime.y);
    46.  
    47.             ChooseMoveDirection();
    48.         }
    49.        
    50.     }
    51.  
    52.     void ChooseMoveDirection()
    53.     {
    54.         currentMoveDiretion = Mathf.FloorToInt(Random.Range(0, moveDirections.Length));
    55.     }
    56.  
    57.     private void FixedUpdate()
    58.     {
    59.         Vector2 pos = rb.position;
    60.     }
    61.     private void OnCollisionEnter2D(Collision2D collision)
    62.     {
    63.         Vector2 pos = rb.position;
    64.         int loops = 0;
    65.         ChooseMoveDirection();
    66.         while (pos == rb.position && loops < 100)
    67.         {
    68.             loops++;
    69.             ChooseMoveDirection();
    70.         }
    71.  
    72.     }
    73. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Line 66 compares a Vector3 position for equality so it is unlikely to ever succeed the way you expect it to due to floating point imprecision. Instead of checking for equality, check for Vector3.Distance() being "small enough," whatever that means in your context.

    Beyond that, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?

    Knowing this information will help you reason about the behavior you are seeing.

    You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494