Unity3D学习笔记-------小地图制作
制作小地图首先需要两个贴图:第一个贴图是小地图的背景贴图,它应当是从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 }