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 Issues changing to horizontal and vertical sprites when using on-screen joystick...

Discussion in 'Scripting' started by NovaCentauri, May 17, 2023.

  1. NovaCentauri

    NovaCentauri

    Joined:
    Dec 19, 2022
    Posts:
    7
    I am currently working on a top-down 2d pixel style mobile game, with the player being able to move in 8 directions.

    Please see my code below, my initial setup for how the player sprites are rendered uses 5 directional sprites (for north, north-east, east, south-east and south) and I have been using spriteRenderer.flipX to mirror those sprites when facing the opposite way on the x axis.

    Updating the player's sprite based on these 8 directions works with no issues when using WASD input, however when I have been trying to implement an on-screen virtual joystick instead of keyboard input, I need to accommodate my code so that it checks for finer floating point values (for example, when the stick is only partially pushed towards a direction) as opposed to the whole or boolean values that the WASD key input returns.

    I have attempted to amend GetSpriteDirection() so that it checks which Cartesian quadrant that the Vector2 ("snap") of the player direction would fall into and then updates the sprite accordingly. However, it appears that North, South and West player movement doesn't update with the correct corresponding sprite, instead it appears to be sticking to the nearest diagonal sprites.

    Somehow I have managed to get the East sprite to update correctly when moving East, however I suspect that the reason the West sprite is not updating in the same way is due to me not using "spriteRenderer.flipX" correctly to flip the sprite when flipping on the x axis.

    If anyone could give me an extra pair of eyes it would be appreciated, I can't work out what I could have missed which is preventing North, South and East sprites from rendering when moving in those directions?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEditor.Experimental.GraphView;
    4. using UnityEngine;
    5. using UnityEngine.UIElements;
    6.  
    7. public class PlayerController : MonoBehaviour
    8. {
    9.     public float moveSpeed = 5f;
    10.     public float collisionOffset = 0.02f;
    11.     public ContactFilter2D movementFilter;
    12.     public Rigidbody2D rb;
    13.     public SpriteRenderer spriteRenderer;
    14.     public Sprite nSprite;
    15.     public Sprite neSprite;
    16.     public Sprite eSprite;
    17.     public Sprite seSprite;
    18.     public Sprite sSprite;
    19.  
    20.     private JoystickController joystick;
    21.     private float angle;
    22.     private float inputX;
    23.     private float inputY;
    24.     private Vector2 input;
    25.     private Vector2 xVector;
    26.     private Vector2 yVector;
    27.     private Vector2 snap;
    28.     readonly List<RaycastHit2D> castCollisions = new();
    29.  
    30.     void Start()
    31.     {
    32.         rb = GetComponent<Rigidbody2D>();
    33.         spriteRenderer = GetComponent<SpriteRenderer>();
    34.         joystick = GameObject.Find("Walk Stick Main").GetComponent<JoystickController>();
    35.     }
    36.  
    37.     private void FixedUpdate()
    38.     {
    39.         inputX = joystick.InputHorizontal();
    40.         inputY = joystick.InputVertical();
    41.         input = new Vector2(inputX, inputY);
    42.         snap = SnapAngle(input, 8);
    43.         HandleSpriteFlip();
    44.         Sprite directionSprite = GetSpriteDirection();
    45.  
    46.         Debug.Log(SnapAngle(input, 8));
    47.  
    48.         if(directionSprite != null)
    49.         {
    50.             // Holding a direction
    51.             spriteRenderer.sprite = directionSprite;
    52.         }
    53.         else
    54.         {
    55.             //  Holding nothing, input is neutral
    56.         }
    57.  
    58.         // If movement input is not 0, try to move
    59.         if (input != Vector2.zero)
    60.         {
    61.  
    62.             bool success = TryMove(snap);
    63.  
    64.             if (!success)
    65.             {
    66.                 xVector = new Vector2(input.x, 0);
    67.                 success = TryMove(SnapAngle(xVector, 8));
    68.  
    69.                 if (!success)
    70.                 {
    71.                     yVector = new Vector2(0, input.y);
    72.                     success = TryMove(SnapAngle(yVector, 8));
    73.                 }
    74.             }
    75.         }
    76.     }
    77.  
    78.     private void HandleSpriteFlip()
    79.     {
    80.         // If we're facing right and the player holds left, flip.
    81.         if (!spriteRenderer.flipX && inputX < 0)
    82.         {
    83.             spriteRenderer.flipX = true;
    84.         }
    85.         else if (spriteRenderer.flipX && inputX > 0)
    86.         {
    87.             spriteRenderer.flipX = false;
    88.         }
    89.     }
    90.  
    91.     Sprite GetSpriteDirection()
    92.     {
    93.         Sprite selectedSprite = null;
    94.  
    95.         if(snap.y > 0) // If North
    96.         {
    97.             if(Mathf.Abs(snap.x) > 0) // With East or West
    98.             {
    99.                 selectedSprite = neSprite;
    100.             }
    101.             else // On its own
    102.             {
    103.                 selectedSprite = nSprite;
    104.             }
    105.         }
    106.         else if (snap.y < 0) // If South
    107.         {
    108.             if (Mathf.Abs(snap.x) > 0) // With East or West
    109.             {
    110.                 selectedSprite = seSprite;
    111.             }
    112.             else // On its own
    113.             {
    114.                 selectedSprite = sSprite;
    115.             }
    116.         }
    117.         else // If East
    118.         {
    119.             if(Mathf.Abs(snap.x) > 0)
    120.             {
    121.                 selectedSprite = eSprite;
    122.             }
    123.         }
    124.         return selectedSprite;
    125.     }
    126.  
    127.     public Vector2 SnapAngle(Vector2 vector, int increments)
    128.     {
    129.         angle = Mathf.Atan2(vector.y, vector.x);
    130.         float direction = ((angle / Mathf.PI) + 1) * 0.5f; // Convert to [0..1] range from [-pi..pi]
    131.         float snappedDirection = Mathf.Round(direction * increments) / increments; // Snap to increment
    132.         snappedDirection = ((snappedDirection * 2) - 1) * Mathf.PI; // Convert back to [-pi..pi] range
    133.         Vector2 snappedVector = new Vector2(Mathf.Cos(snappedDirection), Mathf.Sin(snappedDirection));
    134.         return vector.magnitude * snappedVector;
    135.     }
    136.  
    137.     private bool TryMove(Vector2 direction)
    138.     {
    139.         if (direction != Vector2.zero)
    140.         {
    141.             // Check for potential collisions
    142.             int count = rb.Cast(
    143.                 direction, // X and Y values betweeen -1 and 1 that represent the direction from the body to look for collisions
    144.                 movementFilter, // The settings that determine where a collision can occur at such as layers to collide with
    145.                 castCollisions, // List of collisions to store the found collisions into after the cast is finished
    146.                 moveSpeed * Time.fixedDeltaTime + collisionOffset); // The amount to cast (equal to the movement plus the offset)
    147.             if (count == 0)
    148.             {
    149.                 rb.MovePosition(rb.position + moveSpeed * Time.fixedDeltaTime * direction);
    150.                 return true;
    151.             }
    152.             else
    153.             {
    154.                 return false;
    155.             }
    156.         }
    157.         else
    158.         {
    159.             // Can't move if there's no direction to move in
    160.             return false;
    161.         }
    162.  
    163.     }
    164. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Restructure the code so that it operates in steps:

    - gather raw input
    - quantize it into the 8 directions you want
    - operate on the input

    Enclosed is a quantized input example.
     

    Attached Files:

  3. NovaCentauri

    NovaCentauri

    Joined:
    Dec 19, 2022
    Posts:
    7
    I've checked through my code going off what you said but I'm unsure how I could restructure this further? The original FixedUpdate() method I posted already gathers raw input 1st -----> then quantizes this to 8 directions 2nd (using the SnapAngle() method) -----> then finally tries to move the player and updates the sprite based on the converted input?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    If it's not working then it's just down to basic debugging. That's not the same thing as staring at a piece of code in the forum. Debugging involves you instrumenting or break-pointing the code and running it to find out where it goes wrong.

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

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    NovaCentauri likes this.
  5. NovaCentauri

    NovaCentauri

    Joined:
    Dec 19, 2022
    Posts:
    7
    You can tell I'm new to this cant you... especially when debugging isn't my first place I go :rolleyes: haha. This absolutely fast-tracked me right to the problem! Thank you so much for the priceless advice (and the memorable quote). I shall debug diligently from now on! :)
     
    Kurt-Dekker likes this.