Implementing Camera Movement in Unity

Aug 5, 2024

Camera Movement in 2D Games

Introduction

  • Today's focus: Implementing camera movement in 2D games using Unity.
  • Changes made since the last episode:
    • Adjusted character speed and jump force.
    • Improved running animation.

Camera Setup

  • Current issue: Camera remains stationary while character moves.
  • Solution: Use Cinemachine to create a camera that follows the player.

Installing Cinemachine

  1. Open Package Manager in Unity.
  2. Navigate to Packages in Project and select Unity Registry.
  3. Search for Cinemachine and install it.
  4. A new tab called Cinemachine will appear in the Unity interface.

Creating the Camera

  • Create a new 2D camera:
    1. Go to Cinemachine tab.
    2. Select Create 2D Camera.
  • The new camera (CMVCam1) should be placed under the main camera.
  • This camera will control the main camera.

Configuring the Camera

  • Select the Cinemachine camera in the inspector to configure settings:
    • Follow: Drag the player component to the follow field.
    • Game Window Guide: Activate to visualize what the camera sees.

Understanding the Camera's Movement

  • The yellow dot represents where the camera is looking at. The camera centers on this dot.
  • Catch-up System: Camera adjusts its position after player moves, allowing for a delay.

Key Settings

  1. Look Ahead Time: Adjusts how far the camera looks ahead of the player.
    • Set to 1 for maximum advance view (may feel harsh).
    • A value of 0.5 is recommended for smoother following.
  2. Look Ahead Smoothing: Smoothens the camera's look-ahead movement.
    • Setting to 10 for a smoother experience.
  3. Look Ahead Ignore Y: If enabled, the camera ignores vertical movement while looking ahead.
  4. Damping: Controls how quickly the camera catches up to the player.
    • Setting damping to zero results in instant centering.
  5. Green X and Y Center-ness: Adjusts the center position of the player on-screen.
  6. Dead Zone: Area within which the camera does not follow the player.
    • Increasing the dead zone allows for more player movement without camera movement.
  7. Soft Zone: The region the camera tries to keep the yellow dot within.
    • Prevents the camera from immediately trying to catch up when the player moves.

Testing Camera Settings

  • Make changes to settings outside of play mode to ensure they save.
  • Recommended settings for testing:
    • Look Ahead Time: 0.5
    • Look Ahead Smoothing: 5
    • Damping: 0.6
    • Centering the player lower on the screen: 0.7
    • Minor adjustments to the dead zone.

Conclusion

  • Cinemachine is a powerful tool for camera movement in Unity, requiring no additional downloads.
  • Setting up a camera with Cinemachine is easier and more efficient than hard-coding camera behavior.
  • Final adjustments lead to satisfactory camera movement.
  • Encouragement to explore and use Cinemachine in future projects.