关于这篇文章的命名,实在不知道怎么命名好,大概功能就是:比如一张宽高为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的境况测试下吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 |
using
UnityEngine; using
System.Collections; public
class SimpleSprite : MonoBehaviour { //标准摄像头的高度// public
float standardCameraSize; //标准屏幕的高度// public
float standardHeight; private
float glTopixelRatio; //素材求// public
Material spriteMaterial; //顶点数// private
int verticesCount = 4; // Use this for initialization void
Start () { //计算像素和世界单位的比值// glTopixelRatio = standardCameraSize * 2.0f / standardHeight; initSprite(); } // Update is called once per frame void
Update () {} //根据宽高生成对应的面// private
void initSprite(){ //获取图片的像素宽高// int
pixelHeight = spriteMaterial.mainTexture.height; int
pixelWidth = spriteMaterial.mainTexture.width; Debug.Log( "pixeW:"
+ pixelWidth + ",pixeH:"
+ pixelHeight); //得到MeshFilter对象// MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>(); if (meshFilter == null ){ //为null时,自动添加// meshFilter = gameObject.AddComponent<MeshFilter>(); MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>(); meshRenderer.sharedMaterial = spriteMaterial; } //得到对应的网格对象// Mesh mesh = meshFilter.mesh; //三角形顶点的坐标数组// Vector3[] vertices = new
Vector3[verticesCount]; //得到三角形的数量// int
trianglesCount = verticesCount - 2; //三角形顶点数组// int [] triangles = new
int [verticesCount *3]; float
glWidth = pixelWidth * glTopixelRatio; float
glHeight = pixelHeight * glTopixelRatio; //以当前对象的中心坐标为标准// vertices[0] = new
Vector3(0, 0, 0); vertices[1] = new
Vector3(0, glHeight, 0); vertices[2] = new
Vector3(glWidth, 0, 0); vertices[3] = new
Vector3(glWidth, glHeight, 0); mesh.vertices = vertices; //绑定顶点顺序// triangles[0] = 0; triangles[1] = 1; triangles[2] = 2; triangles[3] = 1; triangles[4] = 3; triangles[5] = 2; mesh.triangles = triangles; mesh.uv = new
Vector2[]{ new
Vector2(0,0), new
Vector2(0,1), new
Vector2(1,0), new
Vector2(1,1)}; } } |
上面是个简单显示一张图片的代码~
下面是测试结果,用ps加张图片(红色圈圈)比比看显示出来的图片宽高是不是和实际像素一样,结果大小是一样的~
尊重他人的劳动成功,原文地址:http://blog.csdn.net/midashao/article/details/8232341
Unity3D之如何创建正确的像素比在屏幕上,布布扣,bubuko.com
原文:http://www.cnblogs.com/tonge/p/3607793.html