Tutorial: Setting up a 3D Fighting Game Camera Using Cinemachine in Unity3D


This is a simple tutorial exploring the use of a Cinemachine camera in Unity3D for a 3D fighting games such as Virtua Fighter or Tekken.  This is by no means the only solution to achieve this; this tutorial just explores methods that I’ve had some success with when prototyping.

Why use a Cinemachine camera? One nice advantage to a Cinemachine camera is that you can blend into other camera views quickly and easily, so, for example, if you have a unique camera animation for a throw or super move intro, you can easily blend to this animation and back to the main camera using Cinemachine by just simply switching the priority of the virtual camera.

This being said, my Cinemachine camera has the following goals:

  • Track the two characters in the environment
  • Rotate as the two characters move around the scene in any direction.
  • Move in and out as the characters get closer and farther apart.

My scene initially looks like this.  I have two characters, a pink fighter and a teal fighter, which will be tracked by my Cinemachine camera setup.

Initial scene setup

Tracking the Characters

To track the characters, I first create a Cinemachine Target Group Camera (Cinemachine -> Create Target Group Camera).  This creates my Cinemachine Virtual Camera as well as a Cinemachine Target Group.

The Cinemachine Target Group allows me to track multiple transforms.  The following is the Cinemachine Target Group Component setup:

The Cinemachine Target Group Setup

I want the position mode to be Group Center and the Rotation Mode to be Manual.  A script will be applied that’ll rotate this later. I use Late Update for the Update Method.

I set both fighter transforms in the target list with the same weight.  I set the radius to about 1.7. Originally, I was experimenting with the Framing Transposer, where this value is very important; however, for now, just making sure this radius is the same for both transforms is the most important.

The Cinemachine Virtual Camera is setup as follows:

Cinemachine Virtual Camera Setup

The camera is setup to follow and look at the target group.  For the body of the virtual camera, I’m using a Transposer. Again, I originally tried a Framing Transposer, however, I found it was really jittery when rotating the camera.  I later read that the Framing Transposer is better for 2D camera usage than 3D, rotated camera use, so I went back to the basic Transposer.

Anyway, the values are pretty similar to the default values, except I lowered the damping to 0.5 per axis and set the Follow Offset to [0, 2, -4.3333333].  This makes it so the camera is 2 units up and -4.33333333 units away from the center of the target group during runtime.

For the Aim, I use “Same as Follow Target” meaning it’ll use the same rotation as the target group’s transform.

Using this initial setup, the camera should appear like this:

The camera setup just following the center of the targets.

Right now, the camera does a pretty decent job tracking the center of the two characters; however, it doesn’t move back to fit them in view when the pink fighter gets a certain distance away and the camera doesn’t rotate as the pink fighter walks around their opponent.

The next section of this tutorial will go over setting up the camera so it both rotates and moves to track the fighters better.

Rotating and Aligning the Camera

To achieve this, instead of fighting with built-in Cinemachine tools, I decided to write a script.  The MonoBehaviour, Align3DCam, is attached to the Target Group GameObject and appears as follows:

Cinemachine Target Group with Align 3D Cam

TA and TB are the two transforms that will be tracked.  In this case, our fighters.

We then reference the virtual camera itself.  Its Transposer Component will be referenced as well, but this reference will be set during Awake.

Framing Normal is the normal vector.  This is set on Awake based on the follow offset of the virtual camera’s Transposer value.

Distance shows the distance between the two tracked transforms; it is serialized in the inspector for debugging purposes.

Transposer Linear Slope and Transposer Linear Offset are two values that represent a simple linear equation (y = mx + b) where x is the distance between the two tracked transforms and y is the distance along the Framing Normal that the virtual camera will be offset.

The framing helpers are used to help create the slope and offset as well as set the minimum allowed distance so that the camera doesn’t move in too closely when the fighters are standing next to one another.

Now, the following is the script used for Align3DCam:

using Cinemachine;
using UnityEngine;

public class Align3DCam : MonoBehaviour
{
    [Tooltip("The transforms the camera attempts to align to.")]
    public Transform tA, tB;

    [Tooltip("The cinemachine camera that will be updated.")]
    public Cinemachine.CinemachineVirtualCamera virtualCamera;

    /// <summary>
    /// The Transposer component of the cinemachine camera.
    /// </summary>
    private Cinemachine.CinemachineTransposer tranposer;

    /// <summary>
    /// Boolean that is set based on whether or not a virtual camera is supplied.
    /// </summary>
    private bool hasVirtualCamera;

    [SerializeField(), Tooltip("The starting normal of the cinemachine transposer.")]
    private Vector3 framingNormal;

    [SerializeField(), Tooltip("The current distance between the two tracked transforms.")]
    float distance;

    [Tooltip("Slope Value (m) of the linear equation used to determine how far the camera should be based on the distance of the tracked transforms.")]
    public float transposerLinearSlope;

    [Tooltip("Offset Value (b) of the linear equation used to determine how far the camera should be based on the distance of the tracked transforms.")]
    public float transposerLinearOffset;

    [Header("Framing helpers")]
    [Tooltip("The minimum distance allowed between the two transforms before the camera stops moving in and out.")]
    public float minDistance;

    [Tooltip("The minimum distance the camera will be from the tracked transforms.")]
    public float minCamDist;

    [Tooltip("A secondary distance between the two transforms used for reference.")]
    public float secondaryDistance;

    [Tooltip("A secondary distance the camera should be at when the tracked transforms are at the secondary distance.")]
    public float secondaryCamDistance;

    /// <summary>
    /// Function to help determine the
    /// </summary>
    [ContextMenu("Calculate Slope")]
    void CalculateSlopes()
    {
        if (virtualCamera == null)
            return;
        tranposer = virtualCamera.GetCinemachineComponent<CinemachineTransposer>();
        if (transposer == null)
            return;

        // If the application is playing, we don't update the minimum values.
        if (!Application.isPlaying)
        {
            // We get the distance between the transforms currently
            minDistance = Vector3.Distance(tA.position, tB.position);
            distance = minDistance;

            // We get the magnitude of the follow offset vector.
            minCamDist = tranposer.m_FollowOffset.magnitude;
        }

        // We calculate the slope ((y2-y1)/(x2-x1))
        transposerLinearSlope = (secondaryCamDistance - minCamDist) / (secondaryDistance - minDistance);

        // We calculate the offset b = y - mx;
        transposerLinearOffset = minCamDist - (transposerLinearSlope * minDistance);
    }

    private void Awake()
    {
        // Determines if a virtual camera is present and active.
        hasVirtualCamera = virtualCamera != null;
        if (hasVirtualCamera)
        {
            transposer = virtualCamera.GetCinemachineComponent<CinemachineTransposer>();

            if (transposer == null)
            {
                hasVirtualCamera = false;
            }
            else
            {
                // Sets the framing normal by the transposer's initial offset.
                framingNormal = tranposer.m_FollowOffset;
                framingNormal.Normalize();
            }
        }
    }

    // Update is called once per frame
    void LateUpdate()
    {
        // Gets the distance between the two tracked transforms.
        Vector3 diff = tA.position - tB.position;
        distance = diff.magnitude;

        // The Y is removed and the vector is normalized.
        diff.y = 0f;
        diff.Normalize();

        // Adjusts the follow offset of the transposer based on the distance between the two tracked transforms, using a minimum value.
        if (hasVirtualCamera)
        {
            tranposer.m_FollowOffset = framingNormal * (Mathf.Max(minDistance, distance) *
                transposerLinearSlope + transposerLinearOffset);
        }

        // If the two transforms are at the same position, we don't do any updating.
        if (Mathf.Approximately(0f, diff.sqrMagnitude))
            return;

        // We create a quaternion that looks in the initial direction and rotate it 90 degrees
        Quaternion q = Quaternion.LookRotation(diff, Vector3.up) * Quaternion.Euler(0, 90, 0);

        // We create a second one that is rotated 180 degrees.
        Quaternion qA = q * Quaternion.Euler(0, 180, 0);

        // We determine the angle between the current rotation and the two previously created rotations.
        float angle = Quaternion.Angle(q, transform.rotation);
        float angleA = Quaternion.Angle(qA, transform.rotation);

        // The transform's rotation is set to whichever one is closer to the current rotation.
        if (angle < angleA)
            transform.rotation = q;
        else
            transform.rotation = qA;
    }
}

The script is rather lengthy, so I’ll summarize it a bit.  It’s essentially doing two things. Offsetting the camera based on the linear equation values and rotating the camera based on the vector between the two tracked transforms.

The slope values are calculated in the CalculateSlope method, which has a ContextMenu attribute, meaning it can be accessed through the right-click menu of the Align3DCam Component.

The Calculate Slope Context Menu Method

What this does is it takes the current distance of the fighters and the magnitude of the cinemachine camera follow offset position to set the minimum distance and minimum camera distance.  The secondary values are then used to calculate Transposer Linear Slope and Transposer Linear Offset.

Now, to get good secondary values, you’ll have to manually adjust them until you have something you like.  If you use Calculate Slope while the game is playing, the minimum values will not be adjusted, so you can test different secondary values out, and then copy the Component and paste its values when you are no longer running.  I could have probably written a more advanced algorithm that uses a bounding box, but for now, I found this got the job done pretty quickly.

When it comes to rotation, the method works by taking the vector between the two transforms, which is found by subtracting the position of TB from TA.  The y value of this vector is then set to 0 and the vector is normalized.  

A quaternion is then created using Quaternion.LookAt, which takes the normalized diff Vector and Vector3.Up to create a rotation that is essentially look in the direction of this vector.  This quaternion is then multiplied by a 90 degree rotation, thus creating a rotation that will look at both characters; however, this assumes that the TA will always be on the left and TB will be on the right.  If they switch sides, such as one fighter jumping over the other, the camera will rotate and snap quickly like this:

How the camera will look if we only care about one Vector

We certainly don’t want that, so we create another quaternion, which is the first quaternion we created and rotate it 180 degrees on the Y axis, essentially, the same rotation looking in the opposite direction.  We then get the angle between both of these quaternions and the camera’s current rotation. Whichever angle is lower, that is the rotation we use. So now, when jumping over the opponent, the camera will no longer pop to keep the pink player on the left side:

The camera no longer forcing the pink player to the left side.

So, once applied with proper values, the cinemachine virtual camera and target group should work as follows:

The Final Result of the 3D Fighter Cinemachine Camera Setup

As the pink player moves around the teal player, the camera rotates.  The camera moves back as the pink player gets farther away and the camera doesn’t snap sharply when jumping over the opponent.  All of the initial goals have been achieved.

Overall, this is a very simple setup, but it’s a good place for setting up a 3D camera for a fighting game using Cinemachine, especially for early prototypes.  Future features that would probably need to be added are collision with objects in the world if scenes are more complex or using a bounding box to frame fighters in more properly, but again, this is a simple approach to get something off the ground.

If you have questions feel free to comment here or send me a tweet to @mattrified. Additionally, a sample can be found on my Patreon.

Leave a comment

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