Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question New to Unity.. movement issues.

Discussion in 'Scripting' started by ccolt92, Aug 22, 2023.

  1. ccolt92

    ccolt92

    Joined:
    Aug 17, 2023
    Posts:
    3
    Code (CSharp):
    1.  
    2.  
    3.     public bool IsValidMove(Vector3 targetPosition)
    4.     {
    5.         Vector3 currentPosition = transform.position;
    6.  
    7.         // Check if the target position is not the same as the current position
    8.         if (targetPosition == currentPosition)
    9.         {
    10.             return false;
    11.         }
    12.  
    13.         // Calculate the Manhattan distance between the current position and the target position
    14.         int manhattanDistance = Mathf.Abs(Mathf.FloorToInt(currentPosition.x - targetPosition.x)) +
    15.                                 Mathf.Abs(Mathf.FloorToInt(currentPosition.y - targetPosition.y));
    16.  
    17.         // Check if the Manhattan distance is within the defined movement range
    18.         switch (highlightPattern)
    19.         {
    20.             case HighlightPattern.Cross:
    21.                 return manhattanDistance < Mathf.Max(customMovementRangeX, customMovementRangeY);
    22.             case HighlightPattern.LShape:
    23.                 return (manhattanDistance == 3 && Mathf.Abs(targetPosition.x - currentPosition.x) == 2) ||
    24.                        (manhattanDistance == 3 && Mathf.Abs(targetPosition.y - currentPosition.y) == 2);
    25.             case HighlightPattern.Custom:
    26.                 return Mathf.Abs(targetPosition.x - currentPosition.x) <= customMovementRangeX &&
    27.                        Mathf.Abs(targetPosition.y - currentPosition.y) <= customMovementRangeY;
    28.             default:
    29.                 return false;
    30.         }
    31.     }
    32.  
    33.     private void HighlightValidMoveTargets()
    34.     {
    35.         // Find all TileClicker components in the scene
    36.         TileClicker[] tiles = FindObjectsOfType<TileClicker>();
    37.  
    38.         // Get the current position of the knight
    39.         Vector3 currentPosition = transform.position;
    40.  
    41.         // Loop through the tiles to determine which are valid move targets
    42.         foreach (TileClicker tile in tiles)
    43.         {
    44.             Vector3 targetPosition = tile.transform.position + offset;
    45.  
    46.             // Check if the target position is the same as the current position (the tile the knight is on)
    47.             if (targetPosition == currentPosition)
    48.             {
    49.                 tile.isMoveTarget = false; // Ignore the current tile
    50.                 continue;
    51.             }
    52.  
    53.             // Check if the target position is a valid move within the specified range and pattern
    54.             int manhattanDistance = Mathf.Abs(Mathf.FloorToInt(currentPosition.x - targetPosition.x)) +
    55.                                     Mathf.Abs(Mathf.FloorToInt(currentPosition.y - targetPosition.y));
    56.  
    57.             switch (highlightPattern)
    58.             {
    59.                 case HighlightPattern.Cross:
    60.                     // Highlight tiles within customMovementRangeX and customMovementRangeY
    61.                     if (manhattanDistance <= Mathf.Max(customMovementRangeX, customMovementRangeY))
    62.                     {
    63.                         tile.isMoveTarget = true;
    64.                     }
    65.                     break;
    66.                 case HighlightPattern.LShape:
    67.                     // Highlight tiles in an L-shape pattern (2 in one direction and 1 perpendicular)
    68.                     if ((manhattanDistance == 3 && Mathf.Abs(targetPosition.x - currentPosition.x) == 2) ||
    69.                         (manhattanDistance == 3 && Mathf.Abs(targetPosition.y - currentPosition.y) == 2))
    70.                     {
    71.                         tile.isMoveTarget = true;
    72.                     }
    73.                     break;
    74.                 case HighlightPattern.Custom:
    75.                     // Highlight tiles within customMovementRangeX and customMovementRangeY
    76.                     if (Mathf.Abs(targetPosition.x - currentPosition.x) <= customMovementRangeX &&
    77.                         Mathf.Abs(targetPosition.y - currentPosition.y) <= customMovementRangeY)
    78.                     {
    79.                         tile.isMoveTarget = true;
    80.                     }
    81.                     break;
    82.             }
    83.         }
    84.     }
    85.  
    My coding is sloppy and uses many references so be kind please :)
    Also if you need the full code to understand what's happening please let me know.

    Right now I'm trying to make my knight have a specific movement pattern so when I click the unit it can move a max of 3 spaces, and I'm getting close, but for some reason no matter what I change either too many tiles are highlighted or not enough.
    I created my gameboard in 2D Unity but it uses z axis from when I manually placed the tiles to create the board. I got it to the point where it's so close that I don't understand how it's not the pattern I need. I even added a customization option so I could change to different patterns.
    No matter what I do (even without the customizations) it highlights too many tiles or not enough as a path. It's only supposed to be moving 3 tiles. (Down, Down, Left) for example. It seems to be taking into account diagonal positioning and I'm not sure how to fix it. The only way I've achieved the closest to the pattern I am wanting is by setting the pattern to Custom and making it 1, 1

    I've attached my current pattern and the pattern I'd like to achieve.. I am just wondering why I am not getting the correct results.


    I can interact with the board, make the knight move to tiles, default to its correct position.. Just having a lot of trouble with this movement pattern.

    Can anyone tell me what I'm doing wrong here?

    My Pattern:
    MyPattern.png

    Desired Pattern:
    Screenshot 2023-08-21 203900.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    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 names of the GameObjects or Components involved?
    - 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.

    Visit Google for how to see console output from builds. 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 for 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.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    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)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    ccolt92 and zevonbiebelbrott like this.
  3. ccolt92

    ccolt92

    Joined:
    Aug 17, 2023
    Posts:
    3
    Thank you so much for the extremely informative reply. I will begin my debugging adventure :)
     
  4. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728

    This looks like you get a new array of all the world tiles, every time this is called? oof...

    I would have that array made(and cached) at map start, so you're only getting it one time.
     
    ccolt92 likes this.
  5. ccolt92

    ccolt92

    Joined:
    Aug 17, 2023
    Posts:
    3

    I see what you're saying and can definitely use the optimization. Thank you.