Why camera isn't following active character?
I'm creating a 2D game. I followed a YouTube tutorial for the character selection. In one scene I select a character and start a game -> another scene. Character selection works fine, but camera is set to follow ,,empty" gameobject with child of the characters. The selected one is active the other isn't so it's not moving. So camera stay still and isn't moving a bit. How do I set the camera to follow the active character?
Character Selection script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CharacterSwitch : MonoBehaviour
{
private GameObject[] characterList;
private int index;
public void Start()
{
index = PlayerPrefs.GetInt("CharacterSelected");
characterList = new GameObject[transform.childCount];
for(int i = 0; i < transform.childCount; i++)
characterList[i] = transform.GetChild(i).gameObject;
foreach(GameObject go in characterList)
go.SetActive(false);
if (characterList[index])
characterList[index].SetActive(true);
}
public void Left()
{
characterList[index].SetActive(false);
index--;
if (index < 0)
index = characterList.Length - 1;
characterList[index].SetActive(true);
}
public void Right()
{
characterList[index].SetActive(false);
index++;
if (index == characterList.Length)
index = 0;
characterList[index].SetActive(true);
}
public void StartGame()
{
PlayerPrefs.SetInt("CharacterSelected", index);
UnityEngine.SceneManagement.SceneManager.LoadScene("SampleScene");
}
}
Camera Script:
using UnityEngine;
using System.Collections;
public class SmoothCamera2D : MonoBehaviour
{
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;
public float xx;
public float yy;
void Update()
{
if (target)
{
Vector3 point = GetComponent<Camera>().WorldToViewportPoint(target.position);
Vector3 delta = target.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(xx, yy, point.z));
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
}
}
Answer by MTSKrishna · Feb 27, 2021 at 07:38 AM
Put the main camera as the child of the active character!
Yea I did that. But the camera wasn't smooth, which I don't like. I figure it out another way.
Your answer
Follow this Question
Related Questions
How to stop the camera when the player has reached the edge of the level? 2 Answers
camera not following target after reload 0 Answers
How to get the camera to follow a prefab? 2 Answers
Camera always behind player 0 Answers
Object follows AR Camera 1 Answer