Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Cinemachine does not follow instantiated player

Discussion in 'Cinemachine' started by cosades334, May 20, 2023.

  1. cosades334

    cosades334

    Joined:
    May 2, 2017
    Posts:
    8
    Hello,

    I have 3 simple GameObjects for a 2D multiplayer game:
    • Main Camera with CinemachineBrain Component
    upload_2023-5-20_13-19-56.png
    • Terrain
    • GameManager with CinemachineVirtualCamera
    upload_2023-5-20_13-20-49.png

    The GameManager Game Object script will instanciate the players and set the virtual camera to follow the player one :

    Code (CSharp):
    1. public class GameManager : MonoBehaviour
    2. {
    3.     // Players management
    4.     public GameObject playerPrefab;
    5.     public Vector3 initialSpawnPosition = new Vector3(1.0f, 1.0f);
    6.  
    7.     GameObject playerOne;
    8.  
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         SpawnPlayer();
    13.     }
    14.  
    15.     private void SpawnPlayer()
    16.     {
    17.         playerOne = Instantiate(playerPrefab, initialSpawnPosition,Quaternion.identity);
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         CinemachineVirtualCamera vcam = GetComponent<CinemachineVirtualCamera>();
    24.         vcam.LookAt = playerOne.transform;
    25.         vcam.Follow = playerOne.transform;
    26.         vcam.gameObject.SetActive(true);
    27.     }
    28. }
    29.  
    I do not know if I need to put the virtual camera parameter in Start() or Update() method ... But it does not work anyway. The player one is not followed by the Cinemachine camera.

    How do I set the Cinemachine virtual camera from this script ?
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,207
    1. You should put all the code in Start, because there's no reason to keep doing it every frame.
    2. In order for the vcam to follow and look at the target, you need to set the Body and Aim algorithms to something other than "Do Nothing". Try "Transposer" and "Composer", respectively.
     
    cosades334 likes this.
  3. cosades334

    cosades334

    Joined:
    May 2, 2017
    Posts:
    8
    Perfect! The algorithms for Body and Aim solve this! Thank you very much! :):):)
    In order to understand the solution, do you have a documentation / tutorial about these attributes ?
     
  4. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,207
    cosades334 likes this.