Unity相機移動之螢幕邊緣檢測
阿新 • • 發佈:2020-02-20
本文例項為大家分享了Unity相機移動之螢幕邊緣檢測的具體程式碼,供大家參考,具體內容如下
功能:
類似LOL 紅警 相機移動方式。
滑鼠移動到螢幕邊緣,相機隨之移動。
當然還有可以加億一點點細節,比如滑鼠指標變化,滾輪推進拉遠視野,中鍵平移視野等。(沒做)。
效果圖:
這裡做了視覺化資料(可以看到限定的螢幕距離),線框內為檢測的距離。
程式碼:
複製指令碼,直接掛載相機上就可以用。
using UnityEngine; /// <summary> /// 相機邊緣移動 /// </summary> [RequireComponent(typeof(Camera))] public class CameraScreenEdgeMove :MonoBehaviour { [Header("使用邊緣移動")] public bool isUseMoveOnScreenEdge = true; /// <summary> /// 開啟除錯 /// </summary> public bool isDebugScreenEdge = true; //移動速度 public float moveSpeed = 1f; /// <summary> /// 距離螢幕邊緣多遠就開始移動相機 /// </summary> public int ScreenEdgeSize = 20; private bool MoveUp; private bool MoveDown; private bool MoveRight; private bool MoveLeft; private Rect RigthRect; private Rect UpRect; private Rect DownRect; private Rect LeftRect; private Material mat; private Vector3 dir = Vector3.zero; private void Start() { CreateLineMaterial(); } private void Update() { if (isUseMoveOnScreenEdge) { UpRect = new Rect(1f,Screen.height - ScreenEdgeSize,Screen.width,ScreenEdgeSize); DownRect = new Rect(1f,1f,ScreenEdgeSize); LeftRect = new Rect(1f,ScreenEdgeSize,Screen.height); RigthRect = new Rect(Screen.width - ScreenEdgeSize,Screen.height); MoveUp = (UpRect.Contains(Input.mousePosition)); MoveDown = (DownRect.Contains(Input.mousePosition)); MoveLeft = (LeftRect.Contains(Input.mousePosition)); MoveRight = (RigthRect.Contains(Input.mousePosition)); dir.z = MoveUp ? 1 : MoveDown ? -1 : 0; dir.x = MoveLeft ? -1 : MoveRight ? 1 : 0; transform.position = Vector3.Lerp(transform.position,transform.position + dir * moveSpeed,Time.deltaTime); } } void CreateLineMaterial() { if (!mat) { Shader shader = Shader.Find("Hidden/Internal-Colored"); mat = new Material(shader); mat.hideFlags = HideFlags.HideAndDontSave; mat.SetInt("_SrcBlend",(int)UnityEngine.Rendering.BlendMode.SrcAlpha); mat.SetInt("_DstBlend",(int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); mat.SetInt("_Cull",(int)UnityEngine.Rendering.CullMode.Off); mat.SetInt("_ZWrite",0); } } void OnPostRender() { if (isUseMoveOnScreenEdge && isDebugScreenEdge) { DrawRect(UpRect,MoveUp,Color.cyan,Color.red); DrawRect(DownRect,MoveDown,Color.green,Color.red); DrawRect(LeftRect,MoveLeft,Color.yellow,Color.red); DrawRect(RigthRect,MoveRight,Color.blue,Color.red); } } private void DrawRect(Rect rect,bool isMouseEnter,Color normalColor,Color HeighLightColor) { if (isMouseEnter) { DrawScreenRect(rect,HeighLightColor); } else { DrawScreenRect(rect,normalColor); } } private void DrawScreenRect(Rect rect,Color color) { GL.LoadOrtho(); GL.Begin(GL.LINES); { mat.SetPass(0); GL.Color(color); GL.Vertex3(rect.xMin / Screen.width,rect.yMin / Screen.height,0); GL.Vertex3(rect.xMin / Screen.width,rect.yMax / Screen.height,0); GL.Vertex3(rect.xMin / Screen.width,0); GL.Vertex3(rect.xMax / Screen.width,0); GL.Vertex3(rect.xMax / Screen.width,0); } GL.End(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。