Search Unity

Prevent camera approaching the player when it walks backwards? (CM_FreeLook)

Discussion in 'Cinemachine' started by IEdge, Dec 18, 2018.

  1. IEdge

    IEdge

    Joined:
    Mar 25, 2017
    Posts:
    51
    Hello again! Is there any way to prevent the camera approaching the player when it walks backwards?
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,711
    You mean have something like a "minimum distance to target" on the vcam?
     
  3. IEdge

    IEdge

    Joined:
    Mar 25, 2017
    Posts:
    51
    Yes, I need to maintain a certain distance between the player (when it walk backwards) and the vcam except when it collides with walls. I have noted that distance is very close.
     
  4. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,711
    You can try adding a CinemachineExtension. Make sure it comes before CinemachineCollider if you want collider to still work.

    Maybe this will work. Drop it into your scene and select it from the vcam's Extensions menu in the inspector.
    Code (CSharp):
    1. using UnityEngine;
    2. using Cinemachine;
    3.  
    4. /// <summary>
    5. /// An add-on module for Cinemachine Virtual Camera that clamps target disatance
    6. /// </summary>
    7. [ExecuteInEditMode] [SaveDuringPlay] [AddComponentMenu("")] // Hide in menu
    8. public class ClampVcamDistance : CinemachineExtension
    9. {
    10.     [Tooltip("Clamp the vcam's distance from the target to at least this amount")]
    11.     public float m_MinDistance = 10;
    12.  
    13.     private void OnValidate()
    14.     {
    15.         m_MinDistance = Mathf.Max(0, m_MinDistance);
    16.     }
    17.  
    18.     protected override void PostPipelineStageCallback(
    19.         CinemachineVirtualCameraBase vcam,
    20.         CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
    21.     {
    22.         if (stage == CinemachineCore.Stage.Body && VirtualCamera.Follow != null)
    23.         {
    24.             var dir = state.RawPosition - VirtualCamera.Follow.position;
    25.             float d = dir.magnitude;
    26.             if (d < m_MinDistance)
    27.                 state.RawPosition = VirtualCamera.Follow.position + dir.normalized * m_MinDistance;
    28.         }
    29.     }
    30. }
    31.  
     
  5. IEdge

    IEdge

    Joined:
    Mar 25, 2017
    Posts:
    51