unity3d随笔-6

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour {
    public float distance = 18;//距离
    public float rot = 0;//横向弧度
    private float roll=	30f* Mathf.PI / 180;//纵向弧度,与地面成30度角的相机
    private GameObject target;//目标物体
    public float rotSpeed = 0.2f;
    public float rollSpeed = 0.2f;
    private float maxRoll = 70f * Mathf.PI / 180;
    private float minRoll = 10f * Mathf.PI / 180;
    public float maxDistance = 22f;
    public float minDistance = 5f;
    public float zoomSpeed = 0.2f;


	// Use this for initialization
	void Start () {
        target = GameObject.Find("tank");

	}

    void Rotate()
    {//鼠标旋转
        //横向旋转
        float w1 = Input.GetAxis("Mouse X") * rotSpeed;
        rot -= w1;
        //纵向旋转
        float w2 = Input.GetAxis("Mouse Y") * rollSpeed * 0.5f;
        roll -= w2;
        if (roll > maxRoll)
        {
            roll = maxRoll;
        }
        else if(roll<minRoll)
        {
            roll = minRoll;
        }
        //调整距离
        float w3 = Input.GetAxis("Mouse ScrollWheel");
        if (w3 > 0)//向下滚动
        {
            if (distance > minDistance) distance -= zoomSpeed;
        }
        else if (w3 < 0)
        {
            if (distance < maxDistance) distance += zoomSpeed;
        }
    }
	

	void LateUpdate () {

        if (target == null)
        {//找不到目标物体
            return;
        }
        if (Camera.main == null)
        {//找不到主摄像机
            return;
        }
        Rotate();
        //目标位置
        Vector3 targetPos = target.transform.position;
        //相机位置
        Vector3 cameraPos;
        float yz_d = distance * Mathf.Cos(roll);
        float height = distance * Mathf.Sin(roll);
        cameraPos.y = targetPos.y + height;
        cameraPos.z = targetPos.z + yz_d * Mathf.Sin(rot);
        cameraPos.x = targetPos.x + yz_d * Mathf.Cos(rot);
        Camera.main.transform.position = cameraPos;
        //对准目标
        Camera.main.transform.LookAt(target.transform);

		
	}
    public void SetTarget(GameObject target)
    {
        if (target.transform.FindChild("cameraPoint"))
        {
            this.target = target.transform.FindChild("cameraPoint").gameObject;
        }
        else
        {
            this.target = target;
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值