I have created a game in which X characters can be handled at the same time in the same way and they can die at any time. My problem comes when I want the game camera to encompass all these gameobjects.
I have thought that a good option is to calculate the central point between the gameobjects that are in the scene and make the camera follow that point at a certain distance.
I already have the code for the camera, but I need to know how I get that center point or if there is another feasible way to do this. In addition, the camera does not follow any of the axes (X,Y,Z) in a linear way, since it is placed in such a way that an isometric view is seen (the game is in 3D).
As a last important fact, it is that all the gameobjects that are running in the game (that are alive), are saved in a public static List<GameObject>
to be able to access the components of these gameobjects at any time. Also, if a character (gameobject) dies or is born, the list is updated without problems.
I leave you a graphic example with three different cases, the black points being the characters in the scene (gameobjects) and the red points, the central point (vector) that I would like to achieve.
In addition, I leave you the code of the camera so that you can test if you have any solution:
public class Camera_Movement : MonoBehaviour {
Vector3 newPos;
public static List<GameObject> playersInGame = new List<GameObject>();
void Update() {
// Obtener vector central
// Sustituir playersInGame[0].transform.position por el vector central
//newPos = Vector3.Lerp(gameObject.transform.position, "vector central", Time.deltaTime);
newPos = Vector3.Lerp(gameObject.transform.position, playersInGame[0].transform.position, Time.deltaTime);
gameObject.transform.position = new Vector3(newPos.x, newPos.y, newPos.z);
}
}
Thank you very much in advance!
In the end, the solution is simpler than I thought. He just needed to apply the basic math that, due to exhaustion, he hadn't even thought about and thanks to a StackOverflow partner , I've managed to make it work.
Here the end result:
This camera doesn't zoom-in/zoom-out , if a gameobject happens to be out of the camera's view, but that would be a nice update to the code above. If someone wants to include it and succeeds, please edit this answer and share it with the entire community.
Thank you very much to all!
NOTE: The original post is published on StackOverflow in English. I have published it here because I find it interesting to expand the community in Spanish with questions that have not been resolved or asked.