57 lines
1.3 KiB
C#
57 lines
1.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
using static System.Math;
|
|
using static UnityEngine.Mathf;
|
|
|
|
public class CameraOperator : MonoBehaviour
|
|
{
|
|
private Dictionary<int, GameObject> players = new Dictionary<int, GameObject>();
|
|
|
|
public void AddPlayer(GameObject player)
|
|
{
|
|
players[player.GetInstanceID()] = player;
|
|
}
|
|
|
|
public void RemovePlayer(int id)
|
|
{
|
|
players.Remove(id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rotates the camera to point at the center between the players.
|
|
/// </summary>
|
|
void LateUpdate()
|
|
{
|
|
if (players.Count < 1)
|
|
{
|
|
return;
|
|
}
|
|
float x = 0;
|
|
float y = 0;
|
|
float z = 30;
|
|
foreach (GameObject p in players.Values)
|
|
{
|
|
if (p.IsDestroyed())
|
|
continue;
|
|
Vector3 position = p.transform.localPosition;
|
|
z = position.z;
|
|
x += position.x;
|
|
y += position.y;
|
|
}
|
|
x /= players.Count();
|
|
y /= players.Count();
|
|
float a = z - transform.localPosition.z;
|
|
float cXAxis = (float)Sqrt(Pow(a, 2) + Pow(x, 2));
|
|
float cYAxis = (float)Sqrt(Pow(a, 2) + Pow(y, 2));
|
|
Vector3 xyRotation = new Vector3(Rad2Deg * Acos(a / cYAxis) * -Math.Sign(y),
|
|
Rad2Deg * Acos(a / cXAxis) * Math.Sign(x), 0);
|
|
if (transform.localEulerAngles != xyRotation / 2)
|
|
{
|
|
transform.localEulerAngles = xyRotation / 2;
|
|
}
|
|
}
|
|
}
|