Space-Smash-Out/Assets/Scripts/CameraOperator.cs

56 lines
1.2 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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);
}
// Update is called once per frame
void LateUpdate()
{
if (players.Count < 1)
{
return;
}
float x = 1;
float y = 1;
float z = 30;
foreach (GameObject p in players.Values)
{
if (p.IsDestroyed())
continue;
Vector3 position = p.transform.position;
z = position.z;
x += position.x;
y += position.y;
}
x /= players.Count();
y /= players.Count();
float a = 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.eulerAngles != xyRotation / 2)
{
transform.eulerAngles = xyRotation / 2;
}
}
}