- Home /
How to make a camera that follows more than one character?
I have some Jelly characters moving togheter on a grid, like miniatures on a game board. Since the board is very large and every Jelly is an human player, they must be all visible on the screen. So, I need the camera to zoom in and out, and follow smoothly the Jellies to watch the entre area covered by the players.
How can I do that? I am really clueless on this.
Answer by equalsequals · Sep 16, 2010 at 08:45 PM
To get you started, you should be able to use some straight forward Vector3 calculations to find a center point between all of the players' positions.
From there you should make that Vector3 the target of your camera so it follows/centers on it. To tackle the zoom, since you should know all the players positions already, you could find the 2 who are farthest apart from each other and use that when calculating where your camera should be on the Y axis.
[EDIT]
In response to your comment...
You could use the Mesh class to create a mesh that uses all of the player's transform.position Vector3's as it's vertices.
From there, you can use the Mesh.bounds property to return an Axis Aligned Bounding Box (AABB) which you can use the Bounds.center property (a Vector3) as the focal point of your camera. Then, because you have an AABB, the larger the number, the further out your camera should be, and vice-versa.
Here's a little something to get you started:
using UnityEngine; using System.Collections;
public class FramePlayers : MonoBehaviour {
//set this in the inspector
public Transform[] playerLocs;
private Mesh m;
void Update () {
//need a new mesh every frame
m = new Mesh();
//new set of vector3s aswell
Vector3[] v3s = new Vector3[playerLocs.Length];
//populate
for(int i = 0; i < playerLocs.Length; i++)
{
v3s[i] = playerLocs[i].position;
}
//asign them to the mesh
m.vertices = v3s;
//print the resulting AABB's center. I tested this with an even and odd number of transforms.
print(m.bounds.center + "is the center of this mesh.");
}
}
Hope that helps.
==
This is exactly what I already thought to do, but the problems is: what are these Vector3 calculations?
I thought to build an imaginary polygon where players are the vertices. The polygon's barycentre will obviously be the point where camera looks. Then, I should cycle between all players to find who are the farthest, and consequently change the zoom according to the distance.
Unfortunately, the only thing I found to achieve all of this is a piece of code that calculates the distance between 2 objects. At this point, I really don't know where to start...
Thanks for the code help, I'll try it as soon as possible!