zoukankan      html  css  js  c++  java
  • 相机跟随

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

    相机跟随的移动一般写在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;
    		}
    	}
    }
    



  • 相关阅读:
    敏捷实践12 条原则
    源代码就是设计
    什么是软件设计?
    极限编程与敏捷开发
    Windows下配置Nginx代理Django
    你的评估是我的决策
    JavaScript通用库(一)
    系统分层组织结构
    ASP.NET MVC 4 小项目开发总结
    非等值折半查找
  • 原文地址:https://www.cnblogs.com/AlinaL/p/12852165.html
Copyright © 2011-2022 走看看