Skip to content
Wonderful Code See
Wonderful Code See

Master the Code, Shape Your Future

  • Home
  • IT Consulting
  • Artificial Intelligence
  • CS Fundamentals
    • Data Structure and Algorithm
    • Computer Network
  • System Design
  • Programming
    • Python Stack
    • .NET Stack
    • Mobile App Development
    • Web Development
    • Unity Tutorials
  • Technology Business
    • Website building tutorials
  • IDE and OA
  • Dev News
Wonderful Code See

Master the Code, Shape Your Future

Unity in Practice 0012 – Blend Tree in Unity

WCSee, May 10, 2025May 17, 2025

A Blend Tree is a feature within Unity’s Animator Controller that allows you to smoothly transition between multiple animations based on one or more parameters (like speed, direction, or vertical velocity). It’s ideal for creating fluid and natural character movement.


🎯 Common Use Cases

ScenarioDescription
Walk/Run TransitionBlend idle, walk, and run animations based on speed.
Jump & Fall AnimationUse velocityY to blend between jump, mid-air, and fall states.
Directional MovementBlend 2D directional inputs (Horizontal, Vertical) for 8-way movement.
Action IntensityVary animation strength (e.g. light, medium, heavy attacks).

🧱 Blend Tree Types

✅ 1D Blend Tree

  • Uses a single parameter (e.g., speed, velocityY).
  • Best for linear transitions like walk → run or jump → fall.

✅ 2D Blend Tree

  • Uses two parameters (e.g., Horizontal, Vertical).
  • Ideal for directional movement (e.g., top-down 8-direction walk).

Types:

  • 2D Simple Directional – Basic directions
  • 2D Freeform Directional – Smooth, angle-based blending
  • 2D Cartesian – Blending based on X/Y grid values

⚙️ How to Create a Blend Tree

  1. Open your Animator Controller.
  2. Right-click → Create State → From New Blend Tree.
  3. Double-click the Blend Tree to configure it.
  4. Set the Blend Type (1D or 2D).
  5. Assign the Blend Parameter (e.g., velocityY).
  6. Add animation clips and define their thresholds.
  7. Add transitions into/out of the Blend Tree (e.g., isGrounded == false).

🧪 Example: 1D Jump/Fall Blend Tree

Continue with previous demo, let’s add Jump and Fall animation with Blend Tree:

   private void AnimatePlayer()
   {
       // Animate player running
       bool isRun = rb.velocity.x != 0;
      
       // New Added code to set yVelocity parameter
       playerAnim.SetFloat("yVelocity", rb.velocity.y);

       playerAnim.SetBool("isRun", isRun);
       playerAnim.SetBool("isGrounded", isGrounded);   
   }

Full Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerScript : MonoBehaviour
{

    private Rigidbody2D rb;
    private Animator playerAnim;

    [SerializeField] private float moveSpeed = 5;
    [SerializeField] private float jumpForce = 10;

    private float xInput;

    private int facingDirection = 1;
    private bool facingRight = true;

    [Header("Collision Info")]
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private float groundCheckDistance;
    private bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        playerAnim = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckInput();

        CollisionChecks();

        Movement();

        // Flip the player based on input direction
        FlipController();

        AnimatePlayer();
    }


    private void CollisionChecks()
    {
        isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, groundLayer);
    }

    private void CheckInput()
    {
        // Get horizontal input
        xInput = Input.GetAxis("Horizontal");

        // Jump on Space key press
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    private void Movement()
    {
        // Apply horizontal movement
        rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
    }

    private void Jump()
    {
        if (isGrounded)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
    }

    private void AnimatePlayer()
    {
        // Animate player running
        bool isRun = rb.velocity.x != 0;

        playerAnim.SetFloat("yVelocity", rb.velocity.y);

        playerAnim.SetBool("isRun", isRun);
        playerAnim.SetBool("isGrounded", isGrounded);   
    }

    private void Flip()
    {
        facingDirection = facingDirection * -1;
        facingRight = !facingRight;

        transform.Rotate(0, 180, 0);
    }

    private void FlipController()
    {
        if (rb.velocity.x > 0 && !facingRight)
        {
            Flip();
        }
        else if (rb.velocity.x < 0 && facingRight)
        {
            Flip();
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawLine(transform.position, new Vector3(transform.position.x, transform.position.y - groundCheckDistance));

    }
}

✅ Benefits

  • Smooth transitions without manually configuring multiple state links.
  • Scalable structure—easy to extend with more motions or complexity.
  • Cleaner logic—ideal for continuous actions like speed, jump height, or direction.
Please follow and like us:
RSS
Facebook
Facebook
fb-share-icon
X (Twitter)
Visit Us
Follow Me
Tweet
Pinterest
Pinterest
fb-share-icon
Post Views: 121

Related posts:

Unity in Practice 0014 – Unity 2D Dash and Dash Cooldown with Time.deltaTime Unity in Practice 0011 – Player Jump with Ground Check in Unity Unity in Practice 0010 – Flipping a 2D Character Horizontally in Unity Unity in Practice 0009 – How to Use Sprite Sheets in Unity for 2D Animation and UI Unity in Practice 0007 – Very First Unity C# Code to Move and Jump a 2D Ball Unity in Practice 0008 – Encapsulation and Inspector Access with Unity’s [SerializeField] Unity in Practice 0005 – Create C# Script Unity in Practice 0006 – Very first C# code to demonstrate how to capture input
Unity Tutorials Blend TreeGame DevelopmentUnity Blend TreeUnity Game Development

Post navigation

Previous post
Next post

Leave a Reply Cancel reply

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

Recent Posts

  • Set Up and Customize Website Using WordPress | Building Website Tutorials Part 4
  • How to Export Wide Excel sheet to PDF Without Cutting Columns
  • Register a Domain Name and Set Up Hosting | Building Website Tutorials Part 3
  • Choose the Right Website Platform or Builder | Building Website Tutorials Part 2
  • Define Your Website Purpose Clearly | Building Website Tutorials Part 1
  • How to Build a Website from Scratch (Step-by-Step Guide for Beginners)
  • IT Due Diligence and IT Audit: What’s the Differences
  • How to Check SSL/TLS Versions and Cipher Suites on macOS and Windows
  • IT Audit Guide Part 8: IT Audit Best Practices
  • IT Audit Guide Part 7: IT Audit Deliverables

Recent Comments

    Categories

    • CS Fundamentals (1)
      • Computer Network (1)
    • IDE and OA Tool Tips (1)
    • IT Consulting (24)
    • Programming (16)
      • Python Stack (1)
      • Unity Tutorials (15)
    • System Design (1)
    • Technology Business (6)
      • Website building tutorials (5)

    Archives

    • May 2025 (49)
    ©2025 Wonderful Code See | WordPress Theme by SuperbThemes
    Manage Consent
    To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
    Functional Always active
    The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
    Preferences
    The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
    Statistics
    The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
    Marketing
    The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
    Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
    View preferences
    {title} {title} {title}