Search Unity

Question Help with an object's child rotation

Discussion in 'Scripting' started by K4ution, Dec 4, 2022.

  1. K4ution

    K4ution

    Joined:
    Mar 15, 2021
    Posts:
    4
    Hello all,

    I have an NPC patrolling a list of transforms and when reaching the last one he waits for 3 seconds and then turns around and goes through the list but backwards, I'm using a bool (forward) to know to which direction he is moving

    Code (CSharp):
    1.  
    2. public class ParentController : MonoBehaviour
    3. {
    4.     List<Transform> waypoints;
    5.     [SerializeField] int waypointIndex = 0;
    6.     [SerializeField] Transform pathPrefab;
    7.     [SerializeField] float moveSpeed;
    8.     [SerializeField] int waitTime;
    9.     Vector3 targetPosition;
    10.     [SerializeField] bool forward = true;
    11.     bool llamada = false;
    12.     Transform pivot;
    13.     Vector3 lookAt;
    14.  
    15.  
    16.     //pivot.up = targetPosition - pivot.position;
    17.     void Awake()
    18.     {
    19.         waypoints = GetWaypoints();
    20.         pivot = transform.Find("Pivot");
    21.     }
    22.  
    23.    
    24.     void Update()
    25.     {
    26.         MoveParent();
    27.         pivot.up = lookAt;
    28.     }
    29.  
    30.     void MoveParent()
    31.     {
    32.         if(waypointIndex < waypoints.Count && forward)
    33.         {
    34.             Vector3 targetPosition = waypoints[waypointIndex].position;
    35.             lookAt = targetPosition - pivot.position;
    36.             float delta = moveSpeed * Time.deltaTime;
    37.             transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
    38.             if (transform.position == targetPosition)
    39.             {
    40.                 waypointIndex++;
    41.                
    42.                
    43.                 if(waypointIndex == waypoints.Count && !llamada)
    44.                 {
    45.                     StartCoroutine(TurnAround());
    46.                 }
    47.                
    48.             }
    49.         }
    50.         if(waypointIndex >= 0 && !forward)
    51.         {
    52.             Vector3 targetPosition = waypoints[waypointIndex].position;
    53.             lookAt = targetPosition - pivot.position;
    54.             float delta = moveSpeed * Time.deltaTime;
    55.             transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
    56.             if (transform.position == targetPosition)
    57.             {
    58.                 waypointIndex--;
    59.                 if(waypointIndex == -1 && !llamada)
    60.                 {
    61.                     StartCoroutine(TurnAround());
    62.                 }
    63.             }
    64.         }
    65.     }
    66.  
    67.     IEnumerator TurnAround()
    68.     {
    69.         llamada = true;
    70.         yield return new WaitForSecondsRealtime(waitTime);
    71.  
    72.         if(waypointIndex >= waypoints.Count)
    73.         {
    74.             waypointIndex --;
    75.         }
    76.         else
    77.         {
    78.             waypointIndex ++;
    79.         }
    80.  
    81.         forward = !forward;
    82.         llamada = false;
    83.     }
    84.  
    85.     List<Transform> GetWaypoints()
    86.     {
    87.         List<Transform> waypoints = new List<Transform>();
    88.         foreach (Transform child in pathPrefab)
    89.         {
    90.             waypoints.Add(child);
    91.         }
    92.         return waypoints;
    93.     }
    94.  
    95.  
    96. }

    The code could probably be better but it's working, now the issue is that the NPC has a "Vision cone" child attached (referenced in the code as "Pivot").

    Pivot is rotating towards the direction the NPC is moving but when reaching the last and first waypoints the pivot turns to Z = 80.554 and not sure what's causing this and how could I make it so it stays looking at the same direction it was looking before reaching destination.

    Thanks in advance
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    I don't see any rotation code above.

    If you have a Rigidbody on this then you're moving it by transform.position and that is incorrect.

    With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.

    Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.

    https://forum.unity.com/threads/col...-unity-physic-rigidbody.1216875/#post-7763061

    https://forum.unity.com/threads/oncollisionenter2d-not-being-called.1266563/#post-8044121

    If that's not it, welcome to debugging! Here's how to get started:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    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?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

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

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    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, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    IF you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    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

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. K4ution

    K4ution

    Joined:
    Mar 15, 2021
    Posts:
    4

    Hi Kurt,

    The object and his child are not affected by physics, I'm using a collider as a trigger to know when the object is touching the player.

    The code I'm using for rotation is in the update method:

    pivot.up = lookAt;



    pivot is the transform I'm trying to rotate pivot = transform.Find("Pivot"); and lookAt gets calculated inside the MoveParent function:

    lookAt = targetPosition - pivot.position;

    I've taken a look at the code again and the issue was that the lookAt was getting updated before updating the targetPosition, that was making the pivot point the same waypoint he was on until already moving to the next one thus the issue was only visible in the last one because that's were it had to wait before returning.


    Thanks a lot for your time :)
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    AH! Totally missed that.

    Glad you got it sorted.