Unity3D仿照魔兽镜头观察

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3D仿照魔兽镜头观察相关的知识,希望对你有一定的参考价值。

脚本只做了远近缩放,角度移动,未做player移动。脚本需要挂载到MainCamera上,且主角需要设置为Player的Tag。

using UnityEngine;
using System.Collections;

public class follow : MonoBehaviour {

    private Transform player;//主角位置
    private Vector3 offsetPosition;//偏移量
    private bool isRotating = false;//切换旋转方向

    public float distance = 0;//距离
    public float scrollSpeed = 10;//中键,角色拉近速度
    public float rotateSpeed = 2;//角度改变速度



	void Start () {
        player = GameObject.FindGameObjectWithTag("Player").transform;//给player赋值
        transform.LookAt(player.position);//摄像机朝向角色
        offsetPosition = transform.position - player.position;//相机位置-角色位置=偏移量
	}
	
	// Update is called once per frame
	void Update () {
        transform.position = offsetPosition + player.position;//本身位置=偏移量+角色位置(角色移动的时候跟随)
        ScrollView();
        RotateView();
    }


    void ScrollView()
    {
        distance = offsetPosition.magnitude;//偏移量长度(到player的距离)
        distance += -Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
        distance = Mathf.Clamp(distance, 2, 18);//限制最近最远距离
        offsetPosition = offsetPosition.normalized * distance;
//        print(Input.GetAxis("Mouse ScrollWheel"));
    }
    void RotateView()
    {
        //鼠标右键按下
        if (Input.GetMouseButtonDown(1))
        {
            isRotating = true;

        }
        //鼠标右键弹起
        if (Input.GetMouseButtonUp(1))
        {
            isRotating = false;

        }

        if (isRotating)
        {
            Vector3 originalPos = transform.position;//得到MainCamera现在的坐标
            Quaternion originalRotation = transform.rotation;//得到MainCamera现在的旋转情况
            


            transform.RotateAround(player.position, Vector3.up, rotateSpeed * Input.GetAxis("Mouse X"));//X轴转动
            transform.RotateAround(player.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));//Y轴转动

            float x = transform.eulerAngles.x;//得到相机的X欧拉角
            //为限定角度
            if (x < 10 || x > 80)//相机高度不能到角度小于10和大于80的位置
            {
                transform.position = originalPos;
                transform.rotation = originalRotation;

            }

            offsetPosition = transform.position - player.position;//旋转完成后更新偏移量(给跟随player和拉近缩远使用) transform.position

        }
    }
}

知识点:

1.通过FindGameObjectWithTag寻找物体

GameObject.FindGameObjectWithTag("Player")

2.对向量使用的理解

3.限制一个变量的值的范围

Mathf.Clamp(distance, 2, 18)

4.

Input.GetMouseButtonDown(0/1/2)分别为左键/右键/中键

Input.GetAxis("Mouse Y")  //鼠标滑动

Input.GetAxis("Mouse ScrollWheel")//滚轮滑动

6.RotateAround()函数

7.transform.eulerAngles.x //欧拉角


问题:如果使用Vector.right,出现z轴旋转。

以上是关于Unity3D仿照魔兽镜头观察的主要内容,如果未能解决你的问题,请参考以下文章

将实时镜头从摄像机流式传输到 Unity3D

Unity3D镜头抖动怎么做?比如发生爆炸后场景的抖动(用镜头抖动或者画面抖动实现),跪求高手回答!

Unity3d镜头

[Unity3D] 多人游戏中镜头固定角度、随角色移动的实现方式

Unity3D插件Camera Filter Pack插件分享《摄像机镜头特效插件》

Unity3D插件Camera Filter Pack插件分享《摄像机镜头特效插件》