国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > Unity 2D游戏相机控制(水平,竖直,角色居中三种模式)

Unity 2D游戏相机控制(水平,竖直,角色居中三种模式)

来源:程序员人生   发布时间:2015-05-19 08:00:21 阅读次数:5186次
做2D游戏的时候,不过有3种模式,1种是只有竖直向上,1种是只有水平方向,1种是有水平又有竖直方向,我最近做游戏多关卡模式,不同模式就有着不1样的相机控制,依照平时的写法,或许有很多人就1下子写了3个相机脚本,现在我用了1个枚举类型来控制3个不1样的相机,贴代码:
using UnityEngine; using System.Collections; public class CameraCtrl : MonoBehaviour { public enum CameraType { Vertical, Horizontal, Normal } public CameraType cameraType; public float dampTime = 1.5f; public Transform target; // 相机移动速度,初始速度清零 private Vector3 velocity = Vector3.zero; // 相机单例 private static CameraCtrl instance; public static CameraCtrl Instance { get { return instance; } } // 屏幕的默许宽高的1/100 (预编译) #if UNITY_ANDROID private static float devHeight = 8.54f; private static float devWidth = 4.8f; #elif UNITY_IPHONE private static float devHeight = 9.6f; private static float devWidth = 6.4f; #else private static float devHeight = 19.20f; private static float devWidth = 10.80f; #endif // Use this for initialization void Awake () { instance = this; // 屏幕适配 float screenHeight = Screen.height; //Debug.Log ("screenHeight = " + screenHeight); //this.GetComponent<Camera>().orthographicSize = screenHeight / 200.0f; float orthographicSize = this.GetComponent<Camera>().orthographicSize; float aspectRatio = Screen.width * 1.0f / Screen.height; float cameraWidth = orthographicSize * 2 * aspectRatio; //Debug.Log ("cameraWidth = " + cameraWidth); if (cameraWidth < devWidth) { orthographicSize = devWidth / (2 * aspectRatio); Debug.Log ("new orthographicSize = " + orthographicSize); this.GetComponent<Camera>().orthographicSize = orthographicSize; } } // Update is called once per frame void LateUpdate () { if (target) { SetCamera(); } else { SetTarget(); } } // 设置相机 void SetCamera () { Vector3 point = GetComponent<Camera> ().WorldToViewportPoint (target.position); Vector3 delta = target.position - GetComponent<Camera> ().ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, point.z)); Vector3 destination = transform.position + delta; switch (cameraType) { case CameraType.Vertical:// 竖直相机 transform.position = Vector3.SmoothDamp (transform.position, new Vector3 (transform.position.x, destination.y, destination.z), ref velocity, dampTime); break; case CameraType.Horizontal:// 水平相机 transform.position = Vector3.SmoothDamp (transform.position, new Vector3 (destination.x, transform.position.y, destination.z), ref velocity, dampTime); break; case CameraType.Normal:// 无穷制的相机 transform.position = Vector3.SmoothDamp (transform.position, destination, ref velocity, dampTime); break; default: break; } } // 设置目标 void SetTarget () { target = GameObject.FindGameObjectWithTag ("Player").transform; } }

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生