Unity Tutorial: Dynamic Object Displacement with Slider Control

Welcome to another Unity tutorial! In this guide, we’ll explore how to create a dynamic object displacement system using Unity and C#. This system allows you to control the arrangement and displacement of objects within a parent object using a Unity UI Slider. Let’s get started!

Introduction

Have you ever wanted to create a scene where objects dynamically adjust their positions based on a user-controlled slider? In this tutorial, we’ll cover the step-by-step process of building a Unity scene that allows you to displace and arrange objects using a slider. This interactive and visually appealing system can be a great addition to various types of games and simulations.

Step 1: Setting Up the Scene

  1. Open Unity and create a new 3D project.
  2. Import or create a few 3D objects that will be displaced within a parent object.

Step 2: Writing the C# Script

Create a new C# script and attach it to the parent object. This script will handle the displacement of objects based on the Unity UI Slider value. Copy and paste the following code:

using UnityEngine;
using UnityEngine.UI;

public class ObjectDisplacer : MonoBehaviour
{
    public Slider slider;
    public float initialMaxDistance = 5f;
    public float power = 2f;

    private Vector3[] initialPositions;

    void Start()
    {
        UnparentNestedChildren();
        StoreInitialPositions();

        if (slider != null)
        {
            slider.onValueChanged.AddListener(OnSliderValueChanged);
        }
    }

    void UnparentNestedChildren()
    {
        int childCount = transform.childCount;

        for (int i = childCount - 1; i >= 0; i--)
        {
            Transform child = transform.GetChild(i);
            UnparentAndMakeChildrenRecursive(child);
        }
    }

    void UnparentAndMakeChildrenRecursive(Transform parentTransform)
    {
        int childCount = parentTransform.childCount;

        for (int i = childCount - 1; i >= 0; i--)
        {
            Transform child = parentTransform.GetChild(i);
            child.parent = transform;
            UnparentAndMakeChildrenRecursive(child);
        }
    }

    void StoreInitialPositions()
    {
        int childCount = transform.childCount;
        initialPositions = new Vector3[childCount];

        for (int i = 0; i < childCount; i++)
        {
            initialPositions[i] = transform.GetChild(i).localPosition;
        }
    }

    void OnSliderValueChanged(float value)
    {
        float currentMaxDistance = initialMaxDistance * value;
        MoveChildObjects(currentMaxDistance);
    }

    void MoveChildObjects(float maxDistance)
    {
        int childCount = transform.childCount;

        for (int i = 0; i < childCount; i++)
        {
            Transform child = transform.GetChild(i);
            Vector3 initialPosition = initialPositions[i];

            float normalizedX = Mathf.Lerp(0, 1, Mathf.Abs(initialPosition.x) / initialMaxDistance);
            float normalizedY = Mathf.Lerp(0, 1, Mathf.Abs(initialPosition.y) / initialMaxDistance);
            float normalizedZ = Mathf.Lerp(0, 1, Mathf.Abs(initialPosition.z) / initialMaxDistance);

            float displacementX = Mathf.Lerp(0, maxDistance, Mathf.Pow(normalizedX, power));
            float displacementY = Mathf.Lerp(0, maxDistance, Mathf.Pow(normalizedY, power));
            float displacementZ = Mathf.Lerp(0, maxDistance, Mathf.Pow(normalizedZ, power));

            float sideMultiplierX = (initialPosition.x > 0) ? 1f : -1f;
            float sideMultiplierY = (initialPosition.y > 0) ? 1f : -1f;
            float sideMultiplierZ = (initialPosition.z > 0) ? 1f : -1f;

            Vector3 newPosition = initialPosition + new Vector3(sideMultiplierX * displacementX, sideMultiplierY * displacementY, sideMultiplierZ * displacementZ);

            child.localPosition = newPosition;
        }
    }
}

Step 3: Applying the Script

  1. Attach the script to the parent object in the Unity editor.
  2. Assign the Slider reference in the script to a UI Slider in your scene.

Step 4: Testing and Customization

  • Run the scene and observe how the objects dynamically displace based on the slider value.
  • Experiment with different parameters such as initialMaxDistance and power to achieve the desired visual effect.

Conclusion

Congratulations! You’ve successfully created a dynamic object displacement system in Unity. This system provides an interactive way to control the positions of objects within a scene, offering endless possibilities for game development and simulation.

Feel free to customize the script further, add additional features, or integrate it into your existing Unity projects. If you have any questions or suggestions, feel free to leave a comment below. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

Index