相机跟随

几次的相机跟随的练习让我发现我还是需要记录一下不同的相机跟随的实现

相机跟随的移动一般写在LateUpdate里,这样不会造成一些失真现象。

1.在固定位置的相机跟随

public class FollowTarget : MonoBehaviour {

    public Transform character;  //摄像机要跟随的人物
    private Camera mainCamera;//主摄像机

    void Awake()
    {
        mainCamera = Camera.main;
    }

    void FixedUpdate()
    {
        transform.position = character.TransformPoint(new Vector3(0, 4, -5));
        transform.LookAt(character);
    }
}
2.有鼠标滚轮缩进的相机跟随

using UnityEngine;

public class FollowTarget : MonoBehaviour {
	public Transform target;
	Vector3 offset;

	void Update()  
	{
		transform.position = target.position + offset;
		Rotate();
		Scale();
	}


	// Use this for initialization
	void Start()
	{
		offset = transform.position - target.position;
	}

	// Update is called once per frame

	//缩放
	private void Scale()
	{
		float dis = offset.magnitude;
		dis += Input.GetAxis("Mouse ScrollWheel") * 5;
		Debug.Log("dis=" + dis);
		if (dis < 10 || dis > 40)
		{
			return;
		}
		offset = offset.normalized * dis;
	}
	//左右上下移动
	private void Rotate()
	{
		if (Input.GetMouseButton(1))
		{
			Vector3 pos = transform.position;
			Vector3 rot = transform.eulerAngles;

			//围绕原点旋转,也可以将Vector3.zero改为 target.position,就是围绕观察对象旋转
			transform.RotateAround(Vector3.zero, Vector3.up, Input.GetAxis("Mouse X") * 10);
			transform.RotateAround(Vector3.zero, Vector3.left, Input.GetAxis("Mouse Y") * 10);
			float x = transform.eulerAngles.x;
			float y = transform.eulerAngles.y;
			Debug.Log("x=" + x);
			Debug.Log("y=" + y);
			//控制移动范围
			if (x < 20 || x > 45 || y < 0 || y > 40)
			{
				transform.position = pos;
				transform.eulerAngles = rot;
			}
			//  更新相对差值
			offset = transform.position - target.position;
		}
	}
}



posted @ 2018-01-26 11:23  养鼠的猫  阅读(104)  评论(0编辑  收藏  举报