Category: Game Development

  • How to Set Up 2D Movement with Rigidbody Collisions in Unity

    How to Set Up 2D Movement with Rigidbody Collisions in Unity

    When creating 2D games in Unity, setting up smooth player movement that respects game world collisions is essential. In this guide, we’ll walk through the process of building a basic 2D character controller that handles movement and rigidbody collision detection using Unity’s physics system.

    Prerequisites

    • Unity installed (version 2020 or newer recommended)
    • Familiarity with Unity’s basic components
    • Understanding of the Unity physics system (especially Rigidbody2D)

    We will also utilize the new Input System package, so make sure your project has it installed and set up.


    Step 1: Adding Components to the Player

    To begin, ensure your player GameObject has the following components:

    1. Rigidbody2D: Set the body type to Kinematic, as we are moving the player through scripts.
    2. Collider2D: Use a suitable collider such as BoxCollider2D or CapsuleCollider2D to define the player’s collision shape.
    3. PlayerInput: This component integrates with Unity’s new Input System.

    These components ensure that your player GameObject can detect and interact with collision shapes.


    Step 2: Writing the Player Script

    Here’s a complete script for handling player movement and collision detection:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.InputSystem;
    
    public class Player : MonoBehaviour
    {
        public float moveSpeed = 1f;
        public float collisionOffset = 0.05f;
        public ContactFilter2D movementFilter;
    
        private Vector2 moveInput;
        private List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
        private Rigidbody2D rb;
    
        public void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }
    
        public void FixedUpdate()
        {
            bool success = MovePlayer(moveInput);
            if (!success)
            {
                success = MovePlayer(new Vector2(moveInput.x, 0));
                if (!success)
                {
                    success = MovePlayer(new Vector2(0, moveInput.y));
                }
            }
        }
    
        public bool MovePlayer(Vector2 direction)
        {
            int count = rb.Cast(
                direction,
                movementFilter,
                castCollisions,
                moveSpeed * Time.fixedDeltaTime + collisionOffset);
    
            if (count == 0)
            {
                Vector2 moveVector = direction * moveSpeed * Time.fixedDeltaTime;
                rb.MovePosition(rb.position + moveVector);
                return true;
            }
            else
            {
                return false;
            }
        }
    
        public void OnMove(InputValue value)
        {
            moveInput = value.Get<Vector2>();
        }
    
        public void OnFire()
        {
            Debug.Log("Shots fired");
        }
    }
    

    Step 3: Understanding the Key Script Components

    Collision Detection

    The script uses Rigidbody2D.Cast() to check for potential collisions before moving the player.

    • Direction: Determines where to cast the detection ray.
    • Movement Filter: Specifies what layers can block movement.
    • Collision Offset: A small buffer to prevent the player from getting stuck.

    Handling Smooth Movement

    When diagonal movement causes a collision, the player checks horizontal and vertical paths independently, ensuring fluid sliding behavior along obstacles.

    FixedUpdate vs Update

    We use FixedUpdate instead of Update because physics interactions should be handled in FixedUpdate for consistent and accurate results.


    Step 4: Setting Up the Movement Filter

    In Unity, configure the ContactFilter2D by selecting the appropriate collision layers under the Player component’s settings. This ensures the player interacts only with specified objects.


    Step 5: Testing the Movement

    1. Attach the script to your player GameObject.
    2. Set the Rigidbody2D to Kinematic.
    3. Assign movement values for speed and configure the collision offset as needed.
    4. Press Play and test movement.

    Troubleshooting Tips

    • Ensure your player and obstacles have colliders.
    • Verify that the Rigidbody2D component is set to Kinematic.
    • Double-check the layers in the ContactFilter2D settings.

    Conclusion

    By following these steps, you now have a basic player movement setup with collision handling in Unity. This approach provides a smooth and responsive movement system, allowing characters to slide along obstacles and ensuring a more polished gameplay experience. Happy coding!

  • Creating an Animation from Sprite Sheets in Unity

    Creating an Animation from Sprite Sheets in Unity

    Quick Overview

    • Enable 2D Sprite Support: Install the 2D Sprite package via Window > Package Manager.
    • Download the Asset: Grab the free fire animation from Brullov on Itch.io.
    • Import & Configure: Drag the chosen sprite sheet (e.g., burning loop 3) into your project, set its Texture Type to Sprite (2D and UI), and switch Sprite Mode to Multiple.
    • Slice the Sheet: Open the Sprite Editor, choose Grid by Cell Count, enter 6 for columns, then slice and apply.
    • Create the Animation: Drag all the sliced sprites into the scene; Unity will prompt you to save a new animation (e.g., fire_animation.anim).
    • Adjust & Test: Modify the animation speed via the Animator Controller and position/scale the object as needed.

    In-Depth Step-by-Step Guide

    1. Enable the 2D Sprite Package

    Before working with sprite sheets, ensure Unity has the necessary tools:

    1. Navigate to Window > Package Manager.
    2. Select the Unity Registry tab.
    3. Find and install the 2D Sprite package if it’s not already installed.

    2. Download the Fire Animation Asset

    For this tutorial, we use a fire animation asset by Brullov, available for free on Itch.io. You can also support the developer by naming your own price.

    After downloading, unzip the file and locate the orange color folder under Loops.

    3. Importing and Configuring the Sprite Sheet

    1. Import: Drag the chosen sprite sheet (e.g., burning loop 3) into your project’s Materials folder.
    2. Configure: With the sprite sheet selected:
      • Set Texture Type to Sprite (2D and UI).
      • Change Sprite Mode to Multiple.
      • Click Apply in the Inspector.

    4. Slicing the Sprite Sheet

    To prepare your sprite sheet for animation:

    1. Click the Sprite Editor button (visible after configuring the sprite).
    2. If prompted, click OK to apply the settings.
    3. In the Sprite Editor, choose Slice > Grid by Cell Count.
    4. Enter the number of columns as 6 (for our fire animation).
    5. Click Slice and then Apply to finalize the cuts.

    5. Creating the Animation

    1. Drag and Drop: Select all the sliced sprites and drag them into your scene.
    2. Save Animation: Unity will prompt you to create a new animation. Name the file (e.g., fire_animation.anim) and save it in your Animations folder.
    3. Unity automatically creates a looping animation using the provided frames.

    6. Adjusting Animation Properties

    For fine-tuning:

    1. Open the Animator Controller linked with your new animation.
    2. Select the animation clip and adjust the Speed parameter as desired:
      • Increase the speed value to animate faster.
      • Decrease it for a slower, more dramatic effect.
    3. Test your changes by playing the animation in the scene.

    7. Positioning and Testing in Your Scene

    1. Position: Move your animated object to the desired location in your scene (e.g., just above the ground).
    2. Scale: Adjust the Transform component if you need to scale the fire effect (a scaling factor of 3 is a good starting point).
    3. Camera Alignment: Align your camera to focus on the animation via GameObject > Align with View.
    4. Test: Hit the Play button to preview your animation in action.

    Final Thoughts

    This guide provides both a quick reference for experienced developers and a detailed walkthrough for those needing step-by-step instructions. By following these steps, you can efficiently create a looping fire animation from sprite sheets in Unity. Enjoy enhancing your game with dynamic effects, and feel free to experiment further with the animation settings to suit your project’s needs.

    Happy animating!