- Home /
How can I keep three targets in sight, and keep the camera above a specific height - while it resizes?
I have a 2D Orthographic camera for a game that is built similarly to Tennis. I've been working out the code for this, and I think I'm only part of the way so far. At the moment... it... sort-of keeps the two players in frame, with the frame leading more towards the human player - Player One. However, it also has a tendency to drop below the ground level - especially when it zooms out to keep the targets in view. There are three specific targets: The Ball, Player One, and Player Two. I'm probably way off, but this is my existing code:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
// Moving Camera, This Camera tries to follow Player One, Two, and Ball //
public static CameraController Instance;
public Transform PlayerOne;
public Transform PlayerTwo;
public Transform Ball;
public bool Ready = false;
private float MinX = -46.0f;
private float MaxX = 46.0f;
private float MinY = 12.0f;
private float MaxY = 35.0f;
private float LimitFromPlayerX = 20.0f;
private float LimitFromPlayery = 20.0f;
private float DistanceToGround = 0.0f;
private float DistanceFromCenter = 2.0f;
private float Height = 4.0f;
private float Damping = 5f;
private Vector3 EstimatedCameraPosition = Vector3.zero;
private Vector3 WantedPosition = Vector3.zero;
void Awake()
{
Instance = this;
}
public void SetCameraPosition()
{
Vector3 PlayerPosistion = PlayerOne.position;
PlayerPosistion.z = -10.10f;
transform.position = PlayerPosistion;
}
// Update is called once per frame
void FixedUpdate () {
if (Ready) {
Vector3 PlayerPosistion = PlayerOne.position;
PlayerPosistion.z = -10.10f;
Vector3 CameraPosition = transform.position;
CameraPosition.z = -10.10f;
// Get the Distance from the Player to the Ball //
Vector3 WantedPosition = PlayerTwo.transform.position - -PlayerOne.transform.position;
float WPMag = Mathf.Abs(WantedPosition.magnitude);
WPMag = Mathf.Clamp(WPMag, 20, 40);
Debug.Log(WPMag);
Camera.main.orthographicSize = WPMag;
transform.position = Vector3.Lerp(CameraPosition, WantedPosition, Damping * Time.deltaTime);
}
}
void LateUpdate()
{
Vector3 Posit = transform.position;
Posit.x = Mathf.Clamp (Posit.x, MinX, MaxX);
Posit.y = Mathf.Clamp (Posit.y, MinY, MaxY);
transform.position = Posit;
}
Comment