Unity 3D坦克大战案列学习(五)
实现相机视野的跟随
using UnityEngine;
using System.Collections;
/// <summary>
/// 控制相机视野的跟随
/// </summary>
public class FollowTarget : MonoBehaviour
{
public Transform player1;//对象1
public Transform player2;//对象2
private Vector3 offset;//偏移
private Camera camera;//获取相机的组件
// Use this for initialization
void Start ()
{
//计算相机位置减去两个对象的中间位置得到偏移
offset = transform.position - (player1.position + player2.position) / 2;
camera = this.GetComponent<Camera>();//得到相机组件
}
// Update is called once per frame
void Update () {
if(player1 ==null ||player2 ==null) return;
//实时计算两个对象中心位置
transform.position = (player1.position + player2.position) / 2 + offset;
//实时计算两个对象的位置
float distance = Vector3.Distance(player1.position, player2.position);
//保持两个对象位置的比例
float size = distance * 0.6f;
camera.orthographicSize = size;
}
}