制作小地圖首先需要兩個貼圖:第一個貼圖是小地圖的背景貼圖,它應當是從y軸向下俯視截取的貼圖;第二個貼圖是主角位置貼圖,它應當是在背景貼圖之上的小型矩形。
1 using UnityEngine; 2 using System.Collections; 3 4 public class smallMap : MonoBehaviour { 5 // Use this for initialization 6 GameObject plane; //大地圖地形對象 7 GameObject cube; //大地圖主角對象 8 float mapWidth; //大地圖的寬度 9 float mapHeight; //大地圖的高度 10 //地圖邊界檢查 11 float widthCheck; 12 float heightCheck; 13 //小地圖主角位置 14 float mapcube_x = 0; 15 float mapcube_y = 0; 16 //GUI按鈕是否被按下 17 bool keyUp; 18 bool keyDown; 19 bool keyLeft; 20 bool keyRight; 21 22 public Texture map; //小地圖的貼圖 23 public Texture map_cube; //小地圖的主角貼圖 24 void Start () { 25 plane = GameObject.Find("Plane"); 26 cube = GameObject.Find("Cube"); 27 float size_x = plane.GetComponent<MeshFilter>().mesh.bounds.size.x; //得到大地圖的默認寬度 28 float scale_x = plane.transform.localScale.x; //得到大地圖寬度的縮放比例 29 float size_z = plane.GetComponent<MeshFilter>().mesh.bounds.size.z; //得到大地圖的默認高度 30 float scale_z = plane.transform.localScale.z; //得到大地圖高度的縮放比例 31 mapWidth = size_x * scale_x; 32 mapHeight = size_z * scale_z; 33 widthCheck = mapWidth / 2; 34 heightCheck = mapHeight / 2; 35 check(); 36 } 37 38 // Update is called once per frame 39 void Update () { 40 41 } 42 43 void OnGUI() { 44 keyUp = GUILayout.RepeatButton("向前移動"); 45 keyDown = GUILayout.RepeatButton("向后移動"); 46 keyRight = GUILayout.RepeatButton("向右移動"); 47 keyLeft = GUILayout.RepeatButton("向左移動"); 48 GUI.DrawTexture(new Rect(Screen.width - map.width, 0, map.width, map.height), map); 49 GUI.DrawTexture(new Rect(mapcube_x, mapcube_y, map_cube.width, map_cube.height), map_cube); 50 } 51 52 void FixedUpdate() { 53 if (keyUp) { 54 cube.transform.Translate(Vector3.forward * Time.deltaTime * 5); 55 check(); 56 } 57 if (keyDown) { 58 cube.transform.Translate(-Vector3.forward * Time.deltaTime * 5); 59 check(); 60 } 61 if (keyRight) { 62 cube.transform.Translate(Vector3.right * Time.deltaTime * 5); 63 check(); 64 } 65 if (keyLeft) { 66 cube.transform.Translate(Vector3.left * Time.deltaTime * 5); 67 check(); 68 } 69 } 70 71 void check() { 72 float x = cube.transform.position.x; 73 float z = cube.transform.position.z; 74 if (x < -widthCheck) { 75 x = -widthCheck; 76 } 77 if (x > widthCheck) { 78 x = widthCheck; 79 } 80 if (z < -heightCheck) { 81 z = -heightCheck; 82 } 83 if (z > heightCheck) { 84 z = heightCheck; 85 } 86 mapcube_x = (map.width / mapWidth * x) + ((map.width / 2) - (map_cube.width / 2)) + (Screen.width - map.width); 87 mapcube_y = map.height - ((map.height / mapHeight * z) + (map.height / 2)); 88 } 89 }
