Camera matters

Camera matters

·

4 min read

While I am still busy making animations and basic models to prototype the combat system I went on to add a follow camera to the mix.

I soon realised that the camera will impact the basic Player movement script because I need the input to be applied relative to the camera space otherwise it would be a big mess, very hard to control and totally unplayable.

As simple as it might sound this task kept me thinking for a while. I am not very familiar with vector math so translating a (X, Y) input Vector into camera space was quite the challenge. The solution, anyway, is pretty easy: since what I basically want is to map the Input X vector to the forward direction of the camera and the Y to the horizontal, I ended up doing just that: camera.forward and camera.right, multiplied each by their respective Input component. And then I composed a direction Vector3 summing up these individual parts. The result is simple and effective. Here is the relevant extract of my PlayerMovement script:

    var cameraTransform = _camera.transform;
    var targetDir = cameraTransform.right * _inputVector.x + cameraTransform.forward * _inputVector.y;

    // I normalize the resulting vector because what I need is simply the direction.
    // This makes it easy to calibrate the exact movement speed I want as you can
    // see in the following lines
    targetDir.Normalize();

    _velocity = targetDir * (maxMovementSpeed * Time.deltaTime);

    _xzVelocity = new Vector3(_velocity.x, 0, _velocity.z);
    _controller.Move(_velocity);  // _controller is a standard Unity's CharacterController instance

As for the camera itself I went for Cinemachine without much hesitation as it allows for great results with minimal setup. At first I tried the approach suggested by this official video but I quickly realised that the built-in FreeLook Camera is way more indicated for a third person setup like the one I want and I do not have to mess around with an invisible rotating target to handle orbiting.

I quickly setup the LookAt and Follow properties to the Player transform and adjusted the rigs height and radius to feel just right. CM_rigs_setup.png

As mentioned this FreeLook Camera is also supposed to take Input from the player along X and Y axis and translate it automatically into an orbit motion, clamped at the values set in the inspector which is great. Problem is that I am using the "new" Unity Input System so, in order to have it working, I had to add an extra component to my VCam: the CinemachineInputProvider, which is really poorly documented. I hope I will save someone's time but mentioning it here.

Anyway, with that script added, everything worked just fine. And there I had it, a nice, almost effortless Free Look camera.

camera_freelook.gif

Now, back to those animations....