转:http://blog.csdn.net/midashao/article/details/8232341
关于这篇文章的命名,实在不知道怎么命名好,大概功能就是:比如一张宽高为100x100的图片显示在屏幕上,那2D摄像头的Size值为多少时,屏幕上显示出来图片大小和图片的实际像素一致。
这里涉及到一个GL坐标和像素坐标值的转换比,这个比值我们可以自己设置~之后我们设置面上顶点的大小也是依据这个来设置的。
比如上面的图的坐标系是世界坐标,而摄像机的坐标在原点(0,0,0),而且摄像机的Size属性为1那么我们在Size为1,而且屏幕的宽高比为3:2的情况下,摄像机所能看到的范围就如上图中橙色框框那样,也就是所能看到的高度y的世界坐标范围是-1到1,宽度x的世界坐标范围是-1.5到1.5 。那么我们就可以算出世界坐标和像素坐标的比值了。如果我们的屏幕宽高是480x320 (也是3:2的屏幕),那么如果显示在这个屏幕下,上图中,AB两点的高度是320,那么世界坐标高度就和屏幕的高度有个比值,即 2:320 再举个例子,假如有张宽高为100x100的图片,要显示在屏幕上,那它相对的世界坐标是的宽高又是多少呢?根据上面的比值可以算出来:
100 * 2 / 320 = 0.625;
有这个比值,我们在用顶点生成面的时候就用图片的实际像素宽高乘以这个比值就能得到世界坐标的值鸟~
再写个程序简单的显示一张128x128的贴图在2D摄像头的size为1的境况测试下吧
01.using UnityEngine;
02.using System.Collections;
03.
04.public class SimpleSprite : MonoBehaviour {
05.
06. //标准摄像头的高度//
07. public float standardCameraSize;
08.
09. //标准屏幕的高度//
10. public float standardHeight;
11.
12.
13. private float glTopixelRatio;
14.
15.
16.
17. //素材求//
18. public Material spriteMaterial;
19.
20. //顶点数//
21. private int verticesCount = 4;
22.
23.
24.
25.
26. // Use this for initialization
27. void Start () {
28. //计算像素和世界单位的比值//
29. glTopixelRatio = standardCameraSize * 2.0f / standardHeight;
30. initSprite();
31. }
32.
33. // Update is called once per frame
34. void Update () {}
35.
36. //根据宽高生成对应的面//
37. private void initSprite(){
38.
39. //获取图片的像素宽高//
40. int pixelHeight = spriteMaterial.mainTexture.height;
41. int pixelWidth = spriteMaterial.mainTexture.width;
42.
43. Debug.Log("pixeW:" + pixelWidth + ",pixeH:" + pixelHeight);
44.
45. //得到MeshFilter对象//
46. MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
47. if(meshFilter == null){
48. //为null时,自动添加//
49. meshFilter = gameObject.AddComponent<MeshFilter>();
50. MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
51. meshRenderer.sharedMaterial = spriteMaterial;
52. }
53. //得到对应的网格对象//
54. Mesh mesh = meshFilter.mesh;
55.
56. //三角形顶点的坐标数组//
57. Vector3[] vertices = new Vector3[verticesCount];
58.
59. //得到三角形的数量//
60. int trianglesCount = verticesCount - 2;
61.
62. //三角形顶点数组//
63. int[] triangles = new int[verticesCount *3];
64.
65.
66. float glWidth = pixelWidth * glTopixelRatio;
67. float glHeight = pixelHeight * glTopixelRatio;
68.
69.
70.
71. //以当前对象的中心坐标为标准//
72. vertices[0] = new Vector3(0, 0, 0);
73. vertices[1] = new Vector3(0, glHeight, 0);
74. vertices[2] = new Vector3(glWidth, 0, 0);
75. vertices[3] = new Vector3(glWidth, glHeight, 0);
76.
77. mesh.vertices = vertices;
78.
79.
80. //绑定顶点顺序//
81. triangles[0] = 0;
82. triangles[1] = 1;
83. triangles[2] = 2;
84. triangles[3] = 1;
85. triangles[4] = 3;
86. triangles[5] = 2;
87.
88.
89. mesh.triangles = triangles;
90.
91. mesh.uv = new Vector2[]{new Vector2(0,0), new Vector2(0,1), new Vector2(1,0), new Vector2(1,1)};
92.
93.
94. }
95.
96.}