Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

Unity code to show on UI canvas distance to X2 from X1 by moving sprite

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514-thinking-32k’s answer.
  1. User

    Unity code to show on UI canvas distance to X2 from X1 by moving sprite

  2. Gemini Assistant

    This Unity solution will guide you through creating a simple setup where you have two points (X1 and X2), one of which is a moving sprite. The distance between them will be continuously calculated and displayed on a UI Canvas.

    We'll create:

    1. A UI Canvas with a Text element.
    2. An empty GameObject for X1 (the fixed point).
    3. A Sprite GameObject for X2 (the moving point).
    4. A C# script to handle the movement of X2.
    5. A C# script to calculate and display the distance.

    Step-by-Step Setup in Unity

    1. Create a New Unity Project

    • Open Unity Hub, click "New Project".
    • Select "2D Core" or "3D Core" (2D is easier for sprites).
    • Give it a name (e.g., "DistanceCalculator") and create.

    2. Import TextMeshPro Essentials (if using TextMeshPro)

    • When you first add a TextMeshPro UI element, a pop-up will ask to import TMP Essentials. Click "Import TMP Essentials". This is highly recommended for better text rendering.

    3. Set up the UI Canvas and Text

    • In the Hierarchy, right-click -> UI -> Canvas.
    • Select the Canvas in the Hierarchy.
      • In the Inspector, for Canvas Scaler, set:
        • UI Scale Mode: Scale With Screen Size
        • Reference Resolution: 1920 x 1080 (or your preferred resolution)
        • Match: 0.5 (or a value that balances width/height scaling)
    • Right-click on the Canvas in the Hierarchy -> UI -> TextMeshPro - Text (or Legacy Text if you prefer not to use TMP).
      • Select the new Text (TMP) object.
      • In the Inspector:
        • Rename it to DistanceText.
        • Set Rect Transform Pos Y to something like 450 (to place it at the top).
        • Set Text Input to Distance: 0.00 units.
        • Set Font Size to 36 (or suitable size).
        • Set Alignment to Center.
        • Set Color to White or any contrasting color.

    4. Create X1 (Static Point)

    • In the Hierarchy, right-click -> Create Empty.
    • Rename it to X1_FixedPoint.
    • In the Inspector, set its Transform Position to (0, 0, 0) or any desired fixed location.
    • Optional: To visualize X1, you can add a simple Sprite:
      • Right-click X1_FixedPoint -> 2D Object -> Sprites -> Square.
      • Rename it Visual_X1.
      • Set its Sprite Renderer Color to Red.
      • Set its Transform Scale to (0.5, 0.5, 1) to make it smaller.

    5. Create X2 (Moving Sprite)

    • In the Hierarchy, right-click -> 2D Object -> Sprites -> Square.
    • Rename it to X2_MovingSprite.
    • In the Inspector, set its Sprite Renderer Color to Blue.
    • Set its Transform Position to (3, 0, 0) or somewhere different from X1.
    • Set its Transform Scale to (0.5, 0.5, 1).

    Create C# Scripts

    6. Player Movement Script (PlayerMovement.cs) This script will allow you to move X2_MovingSprite using the keyboard (WASD or Arrow keys).

    • In the Project window, right-click -> Create -> C# Script.
    • Name it PlayerMovement.
    • Double-click to open it in your IDE (Visual Studio, Rider, etc.) and paste the following code:
    using UnityEngine;
    
    public class PlayerMovement : MonoBehaviour
    {
        [SerializeField] private float moveSpeed = 5f; // Speed at which the sprite moves
    
        void Update()
        {
            // Get horizontal and vertical input (WASD or Arrow Keys)
            float moveX = Input.GetAxis("Horizontal");
            float moveY = Input.GetAxis("Vertical");
    
            // Create a movement vector based on input
            Vector3 movement = new Vector3(moveX, moveY, 0f);
    
            // Apply movement scaled by speed and time (for frame-rate independence)
            transform.position += movement * moveSpeed * Time.deltaTime;
        }
    }
    
    • Attach PlayerMovement to X2_MovingSprite:
      • Select X2_MovingSprite in the Hierarchy.
      • Drag the PlayerMovement script from the Project window onto X2_MovingSprite in the Inspector.

    7. Distance Calculator Script (DistanceCalculator.cs) This script will calculate the distance between X1 and X2 and update the UI Text.

    • In the Project window, right-click -> Create -> C# Script.
    • Name it DistanceCalculator.
    • Double-click to open it and paste the following code:
    using UnityEngine;
    using TMPro; // Required for TextMeshProUGUI
    
    public class DistanceCalculator : MonoBehaviour
    {
        // SerializeField allows setting these in the Inspector
        [SerializeField] private TextMeshProUGUI distanceText; // Reference to our UI Text element
        [SerializeField] private Transform x1Transform;        // Reference to X1 (Fixed Point) Transform
        [SerializeField] private Transform x2Transform;        // Reference to X2 (Moving Sprite) Transform
    
        void Update()
        {
            // Ensure all references are set before trying to use them
            if (x1Transform != null && x2Transform != null && distanceText != null)
            {
                // Calculate the distance between the positions of X1 and X2
                float distance = Vector3.Distance(x1Transform.position, x2Transform.position);
    
                // Update the UI Text with the calculated distance, formatted to 2 decimal places
                distanceText.text = $"Distance: {distance:F2} units";
            }
            else
            {
                // Log a warning if any references are missing, helpful for debugging
                Debug.LogWarning("DistanceCalculator references not set up! Please assign all in the Inspector.");
            }
        }
    }
    
    • Create an Empty GameObject for the DistanceCalculator script:
      • In the Hierarchy, right-click -> Create Empty.
      • Rename it to GameManager (or DistanceDisplayManager).
    • Attach DistanceCalculator to GameManager:
      • Select GameManager in the Hierarchy.
      • Drag the DistanceCalculator script from the Project window onto GameManager in the Inspector.
    • Assign References in the Inspector:
      • With GameManager selected in the Hierarchy, look at its Inspector.
      • You'll see three empty fields under the DistanceCalculator component:
        • Distance Text: Drag the DistanceText object from the Hierarchy into this field.
        • X1 Transform: Drag the X1_FixedPoint object from the Hierarchy into this field.
        • X2 Transform: Drag the X2_MovingSprite object from the Hierarchy into this field.

    Test Your Scene

    1. Click the Play button at the top of the Unity editor.
    2. You should see your X1_FixedPoint (red square) and X2_MovingSprite (blue square) in the Game view.
    3. The "Distance:" text at the top of the screen should update to show the current distance between them.
    4. Use the WASD or Arrow Keys to move the X2_MovingSprite. Observe how the distance text updates in real-time as you move closer or further from X1_FixedPoint.

    This setup provides a clear and functional way to display the distance between a fixed point and a moving sprite on a Unity UI canvas.

  3. User

    Not text, just sprite

  4. Gemini Assistant

    Okay, you want to show distance using a sprite's scale, rather than text. This is a great way to provide a visual cue!

    We'll make a UI Image (which uses a sprite) that grows or shrinks horizontally based on the distance between X1 and X2.


    Step-by-Step Setup in Unity (Modified)

    1. Create a New Unity Project

    • Same as before.

    2. Set up the UI Canvas

    • In the Hierarchy, right-click -> UI -> Canvas.
    • Select the Canvas in the Hierarchy.
      • In the Inspector, for Canvas Scaler, set:
        • UI Scale Mode: Scale With Screen Size
        • Reference Resolution: 1920 x 1080
        • Match: 0.5

    3. Create the UI Image (Distance Bar)

    • Right-click on the Canvas in the Hierarchy -> UI -> Image.
      • Select the new Image object.
      • In the Inspector:
        • Rename it to DistanceBarImage.
        • Set Rect Transform:
          • Anchor Presets: Click the square icon and choose Middle-Left (or any anchor that suits your desired growth direction, this will make the bar grow rightwards).
          • Pos X: 100 (or suitable for spacing from the edge)
          • Pos Y: 0
          • Width: 10 (initial small width, will be changed by script)
          • Height: 30 (or desired height for the bar)
        • For Image (Script):
          • Source Image: Click the small circle next to "None (Sprite)" and search for UISprite. Select it. (This is a simple white square sprite provided by Unity).
          • Color: Choose a distinct color, like Green or Yellow.

    4. Create X1 (Static Point) & X2 (Moving Sprite)

    • X1_FixedPoint:
      • Right-click in Hierarchy -> Create Empty. Rename to X1_FixedPoint.
      • Set Transform Position to (0, 0, 0).
      • Optional Visual: Add a 2D Object -> Sprites -> Square child named Visual_X1, color Red, scale (0.5, 0.5, 1).
    • X2_MovingSprite:
      • Right-click in Hierarchy -> 2D Object -> Sprites -> Square. Rename to X2_MovingSprite.
      • Set Sprite Renderer Color to Blue.
      • Set Transform Position to (3, 0, 0).
      • Set Transform Scale to (0.5, 0.5, 1).

    5. Player Movement Script (PlayerMovement.cs)

    • This script remains the same as before.
    • In the Project window, create a C# Script named PlayerMovement.
    • Paste the following code:
      using UnityEngine;
      
      public class PlayerMovement : MonoBehaviour
      {
          [SerializeField] private float moveSpeed = 5f;
      
          void Update()
          {
              float moveX = Input.GetAxis("Horizontal");
              float moveY = Input.GetAxis("Vertical");
              Vector3 movement = new Vector3(moveX, moveY, 0f);
              transform.position += movement * moveSpeed * Time.deltaTime;
          }
      }
      
    • Attach PlayerMovement to X2_MovingSprite.

    Create the Distance Visualizer Script (DistanceVisualizer.cs)

    This script will control the width of the UI Image based on distance.

    • In the Project window, right-click -> Create -> C# Script.
    • Name it DistanceVisualizer.
    • Double-click to open it and paste the following code:
    using UnityEngine;
    using UnityEngine.UI; // Required for Image component
    
    public class DistanceVisualizer : MonoBehaviour
    {
        // SerializeField allows setting these in the Inspector
        [SerializeField] private Image distanceBarImage; // Reference to our UI Image element
        [SerializeField] private Transform x1Transform;        // Reference to X1 (Fixed Point) Transform
        [SerializeField] private Transform x2Transform;        // Reference to X2 (Moving Sprite) Transform
    
        [Header("Distance Bar Settings")]
        [Tooltip("The maximum real-world distance that will fully extend the bar.")]
        [SerializeField] private float maxDisplayDistance = 10f; // Distance at which the bar is at max width
    
        [Tooltip("The minimum width of the bar in UI pixels (when distance is 0 or very small).")]
        [SerializeField] private float minBarWidth = 10f; // Bar width when distance is near zero
    
        [Tooltip("The maximum width of the bar in UI pixels (when distance is at or beyond maxDisplayDistance).")]
        [SerializeField] private float maxBarWidth = 400f; // Max width of the bar on UI
    
        void Update()
        {
            // Ensure all references are set before trying to use them
            if (x1Transform != null && x2Transform != null && distanceBarImage != null)
            {
                // Calculate the distance between the positions of X1 and X2
                float currentDistance = Vector3.Distance(x1Transform.position, x2Transform.position);
    
                // Normalize the distance to a 0-1 range
                // InverseLerp maps a value from a range [a, b] to a [0, 1] range.
                // Here, distance 0 maps to 0, and maxDisplayDistance maps to 1.
                float normalizedDistance = Mathf.InverseLerp(0f, maxDisplayDistance, currentDistance);
    
                // Clamp the normalized distance to ensure it stays within 0 and 1
                // This prevents the bar from going beyond maxBarWidth if distance > maxDisplayDistance
                // or smaller than minBarWidth if distance is negative (though distance is always >=0).
                normalizedDistance = Mathf.Clamp01(normalizedDistance);
    
                // Interpolate the bar width based on the normalized distance
                // Lerp maps a [0, 1] value to a range [minBarWidth, maxBarWidth].
                float targetWidth = Mathf.Lerp(minBarWidth, maxBarWidth, normalizedDistance);
    
                // Update the width of the UI Image's RectTransform
                // We only change the width (x), keep the current height (y)
                RectTransform barRectTransform = distanceBarImage.GetComponent<RectTransform>();
                barRectTransform.sizeDelta = new Vector2(targetWidth, barRectTransform.sizeDelta.y);
            }
            else
            {
                Debug.LogWarning("DistanceVisualizer references not set up! Please assign all in the Inspector.");
            }
        }
    }
    
    • Create an Empty GameObject for the DistanceVisualizer script:
      • In the Hierarchy, right-click -> Create Empty.
      • Rename it to GameManager (or DistanceDisplayManager).
    • Attach DistanceVisualizer to GameManager:
      • Select GameManager in the Hierarchy.
      • Drag the DistanceVisualizer script from the Project window onto GameManager in the Inspector.
    • Assign References in the Inspector:
      • With GameManager selected in the Hierarchy, look at its Inspector.
      • You'll see three empty fields under the DistanceVisualizer component, plus the settings for the bar:
        • Distance Bar Image: Drag the DistanceBarImage object from the Hierarchy into this field.
        • X1 Transform: Drag the X1_FixedPoint object from the Hierarchy into this field.
        • X2 Transform: Drag the X2_MovingSprite object from the Hierarchy into this field.
        • Max Display Distance: Set this to a value that makes sense for your game world, e.g., 10 or 20. If the distance goes beyond this, the bar will stay at maxBarWidth.
        • Min Bar Width: 10 (or desired minimum)
        • Max Bar Width: 400 (or desired maximum, this is in UI pixels)

    Test Your Scene

    1. Click the Play button at the top of the Unity editor.
    2. You should see your X1_FixedPoint (red square) and X2_MovingSprite (blue square) in the Game view.
    3. The DistanceBarImage (e.g., green bar) should appear on the UI.
    4. Use the WASD or Arrow Keys to move the X2_MovingSprite.
      • As you move X2_MovingSprite closer to X1_FixedPoint, the green bar will shrink down towards its minBarWidth.
      • As you move X2_MovingSprite further away, the green bar will grow wider until it reaches its maxBarWidth (which happens when the real-world distance hits maxDisplayDistance or more).

    This setup gives you a dynamic visual representation of the distance using a UI sprite! You can swap the UISprite for any custom sprite you've imported to make it look like a meter, health bar, or any other visual indicator.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.