2016. 2. 22. 11:37

Recttransfrom이 가지고있는 SizeDelta 를 = new Vector2로 바꾸시면 됩니다.



rectTransform.sizeDelta = new Vector2( yourWidth, yourHeight);


Posted by 시리시안
2016. 2. 22. 10:38


상단에 Edit -> Project Setting -> Quality 에 들어가서


Rendering에 Texture Quality를 확인합시다.


FullRes로 해주면 깨짐 현상이 없어집니다.


(디폴트 세팅을 판타스틱으로 바꿔주시는게 마음편합니다.)

Posted by 시리시안
2016. 2. 22. 05:54

유니티에서 사운드 재생 하기 위해 만든 매니저입니다.


간단한 사운드부터 거리설정 및 포지션 설정 사운드까지 지원합니다.

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
public class SoundManager : MonoBehaviour
{
 
    public AudioClip[] BGMSounds;
    public AudioClip[] EffectSounds;
 
    public bool isSfxMute = false;
    [Range(0.0f, 1.0f)]
    public float sfxVolume = 1.0f;
 
    public Vector3 SoundPlayPosition;
 
    float DefaultMinDistance = 10.0f;
    float DefaultMaxDistance = 30.0f;
    public void SimplePlayBGM(int Index)
    {
        PlaySfx(BGMSounds[Index]);
    }
    public void SimplePlayEffect(int Index)
    {
        PlaySfx(EffectSounds[Index]);
    }
    public void PlaySfx(AudioClip sfx, Vector3 _pos, float _MinDistance, float _MaxDistance, float _Volume)
    {
        if (isSfxMute) return;
 
        GameObject SoundPlayObject = new GameObject("Sfx_" + sfx.name);
        SoundPlayObject.transform.position = _pos;
 
        AudioSource _AudioSource = SoundPlayObject.AddComponent<AudioSource>();
        _AudioSource.clip = sfx;
        _AudioSource.minDistance = _MinDistance;
        _AudioSource.maxDistance = _MaxDistance;
        _AudioSource.volume = sfxVolume;
 
        _AudioSource.Play();
 
        Destroy(SoundPlayObject, sfx.length);
    }
    public void PlaySfx(AudioClip sfx)
    {
        PlaySfx(sfx,SoundPlayPosition, DefaultMinDistance, DefaultMaxDistance, sfxVolume);
    }
    public void PlaySfx(AudioClip sfx, float _MinDistance, float _MaxDistance)
    {
        PlaySfx(sfx,SoundPlayPosition, _MinDistance, _MaxDistance, sfxVolume);
    }
    public void PlaySfx(AudioClip sfx, Vector3 _pos)
    {
        PlaySfx(sfx, _pos, DefaultMinDistance, DefaultMaxDistance, sfxVolume);
    }
    public void PlaySfx(AudioClip sfx, Vector3 _pos, float _MinDistance, float _MaxDistance)
    {
        PlaySfx(sfx, _pos, _MinDistance, _MaxDistance, sfxVolume);
    }
    public void PlaySfx(AudioClip sfx, Vector3 _pos, float sfxVolume)
    {
        PlaySfx(sfx, _pos, DefaultMinDistance, DefaultMaxDistance, sfxVolume);
    }
}
cs


Posted by 시리시안
2016. 2. 22. 05:53

첨부 파일에 패키지 드립니다.

제가 만든게 아니고, 외국 사이트에서 받은건데..

출처를 알게되면 바로 수정하겠습니다.


spine-unity.unitypackage



Posted by 시리시안
2016. 2. 22. 05:51



저번글에 이어서 봅시다.
이번 글에서는 스파인 좌측 기능에 대해서 볼껍니다.
SkeletonAnimation를 보면 여러 기능을 가지고있네요.
차례대로
스킨, 레이어,어드밴스안에 메시기능과
Z축 거리 노말 연산, 등..
그리고 애니메이션과 루프 타임스케일이 있네요.

위에서부터 봅시다.

스킨은 말그대로 스파인 디자이너가 넣어준 스킨을 교체합니다.
레이어는.. 굳이 설명 안해도 될꺼같네요

어드밴스 부분을 봅시다.
서브매시를 다루는 부분과
Z Spacing이 있네요

먼저 서브메시를 다루는건.. 음.. 내용이 좀 길어 질테니
로 대신합니다.

영상을 그대로 보시고 따라하시면 손쉽게 익히실수 있습니다.

그다음 Z Spacing을 봅시다.
3D뷰로 바꾸고 숫자를 조절하면 바로 알수있을꺼애요




이처럼 2D공간내에서 벌어지게 됩니다.
사용법은.. 서브메시를 이용할때 사용하셔도되고,
일부만 들어가는 파티클 작업이나, 라이트 작업에 사용하셔도됩니다.

그외 노말 과 탄젠트 계산법은 생략할게요.

애니메이션 네임과 루프와 타임스케일은 전부 아실꺼라 생각합니다~


Posted by 시리시안
2016. 2. 22. 05:48
안녕하세요.
먼저 
에서 스파인 SDK를 받습니다.




유니티에 사용하시는거라면 spine-csharp과 spine-unity 2개를 받으면 됩니다.
귀찮으니 그냥 오른쪽 Download ZIP을 눌러서 전부 다운 받읍시다 (22M정도)

그래서 위 2개 폴더를 유니티에 넣어줍시다.







유니티는 스파인파일을 텍스트 파일로 읽기 때문에 .txt로 변경해주어야 합니다.
(아트가 Spine을 잘 다룬다면, .txt로 익스포트시 변경하여 뽑을수도있답니다.)


그다음 Material을 만들고 이미지를 넣어야..하는데..
자동으로 만들어지네요..?
보면 atlas.asset도 자동으로 만들어 집니다........
원래는.. 스파인 아틀라스를 만들고 데이터를 짚어 넣어야 하지만, 자동으로 만들어지니 생략하겠습니다.






아니 다시보니까 
스파인 스켈레톤데이터는 자동으로 안만들어주네요!!?
왜 2개는 자동으로 만들어주고 제일 중요한 파일은 자동이 아닌지..ㅇㅅㅇ;
... 일단 만듭시다.




만든 거기에 atlas 에셋 데이터와 json.txt파일을 넣어줍시다!







Hierarchy에서 SpineSkeletonAnimaion을 만들어줍니다.




그안에 아까 만든 스켈레톤데이터를 넣어줍시다.

그러고 씬을 보면.. 쨔쟌! 벌써 스파인 캐릭터가 등장했네요!!

와..
정말 간단해졌네요 -ㅅ-;


Posted by 시리시안
2016. 2. 22. 05:47


//특정 축 Director
//각도 Dgree = 90.0f
//기준 Space.World
 
//글로벌 기준 회전
transform.Rotate(Director, Dgree, Space.World);
 
//로컬 기준 회전
transform.Rotate(Director, Dgree, Space.Self);
 
//기본적으로 Space.Self 이기 때문에 아무것도 안적어도 됩니다.


Posted by 시리시안
2016. 2. 22. 05:46
1
2
3
4
5
6
7
8
9
10
11
12
private UnityEngine.EventSystems.EventSystem _eventSystem;
 
void Start () {
    _eventSystem = GameObject.Find("EventSystem").GetComponent<UnityEngine.EventSystems.EventSystem>();
}
void OnMouseOver () {
    if(_eventSystem.IsPointerOverEventSystemObject()) {
    // we're over a UI element... peace out
    return;
   }
}
 
cs


Posted by 시리시안
2016. 2. 22. 05:45

PlayerPrefs 클래스는 아주 간단한 방법으로 저장할 정보를입력하면 그걸 자동으로 파일로 저장/불러오기를 해 주는데,

 

Mac OS : ~/Library/Preferences 폴더 안에  unity.[companyname].[product name].plist 라는 이름으로 저장됨

윈도우즈 OS : HKCU\Software\[companyname]\[product name] 레지스트리 안에 저장됨

윈도우즈 웹플레이어 : %APPDATA%\Unity\WebPlayerPrefs안에

Mac 웹플레이어 :~/Library/Preferences/Unity/WebPlayerPrefs

 

이 클래스의 원문 링크는

http://docs.unity3d.com/Documentation/ScriptReference/PlayerPrefs.html

 

사용법

 

 

PlayerPrefs의 인자

 

 voidDeleteAll()                              모든 정보를 삭제한다.

 voidDeleteKey(string key)                  특정 키(정보)를 삭제한다.

 float GetFloat(string key)                     float형 정보를 가져온다.

 float GetFloat(string key, float defaultValue)          float형 정보를 가져오는데그 키에 대한 값이  없으면 defaultValue로 가져온다.

 intGetInt(string key)     int형 정보를 가져온다.

 intGetInt(string key, int defaultValue)      GetFloat과 마찬가지

 string GetString(string key)        string형 정보를 가져온다.

 stringGetString(string key, string defaultValue)      GetFloat과 마찬가지

 boolHasKey(string key)   key가 존재하는가

 voidSave()       PlayerPrefs 클래스에 있는 모든키와 그 정보를

 저장한다.

 voidSetFloat(string key, float value)        float형 값을 클래스에 저장한다.

 voidSetInt(string key, int value)   int형값을 클래스에 저장한다.

 voidSetString(string key, string value)      string형 값을 클래스에 저장한다.

 

 

 

1. 어떤 int 형의숫자 저장하기

 

PlayerPrefs.SetInt("score",score);

PlayerPrefs.Save();

 

PlayerPrefs.SetInt 함수는 인트형 값을 저장하는 함수인데앞의 string은 이 값이 뭔지,즉 변수명이라고 보면 된다뒤의 int 값은어떤 값을 저장할건지를 말한다.

이렇게 PlayerPrefs 클래스에 score의 값을 넣었으면 그걸 파일에 넣기 위해(저장) PlayerPrefs.Save()를 호출한다.

 

 

 

2. 어떤 int 형의값 가져오기

 

int temp =PlayerPrefs.GetInt("score");

 

temp에다가 내가PlayerPrefs로 저장한 값 중 score라는 키를 가진 값을 가져와서 temp에 저장한다

Posted by 시리시안
2016. 2. 22. 05:44
C# - Plane
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// You can change that line to provideanother MeshFilter
MeshFilter filter =gameObject.AddComponent< MeshFilter >();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float length = 1f;
float width = 1f;
int resX = 2// 2 minimum
int resZ = 2;
 
#region Vertices           
Vector3[] vertices = new Vector3[ resX *resZ ];
for(int z = 0; z < resZ; z++)
{
           //[ -length / 2, length / 2 ]
           floatzPos = ((float)z / (resZ - 1- .5f) * length;
           for(intx = 0; x < resX; x++)
           {
                     //[ -width / 2, width / 2 ]
                     floatxPos = ((float)x / (resX - 1- .5f) * width;
                     vertices[x + z * resX ] = new Vector3( xPos, 0f, zPos );
           }
}
#endregion
 
#region Normales
Vector3[] normales = new Vector3[vertices.Length ];
forint n = 0; n < normales.Length; n++)
           normales[n]= Vector3.up;
#endregion
 
#region UVs                
Vector2[] uvs = new Vector2[vertices.Length ];
for(int v = 0; v < resZ; v++)
{
           for(intu = 0; u < resX; u++)
           {
                     uvs[u + v * resX ] = new Vector2( (float)u / (resX - 1), (float)v / (resZ - 1) );
           }
}
#endregion
 
#region Triangles
int nbFaces = (resX - 1* (resZ - 1);
int[] triangles = new int[ nbFaces * 6 ];
int t = 0;
for(int face = 0; face < nbFaces; face++)
{
           //Retrieve lower left corner from face ind
           inti = face % (resX - 1+ (face / (resZ - 1* resX);
 
           triangles[t++]= i + resX;
           triangles[t++]= i + 1;
           triangles[t++]= i;
 
           triangles[t++]= i + resX;
           triangles[t++]= i + resX + 1;
           triangles[t++]= i + 1;
}
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
 
C# - Box
// You can change that line to provideanother MeshFilter
MeshFilter filter =gameObject.AddComponent< MeshFilter >();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float length = 1f;
float width = 1f;
float height = 1f;
 
#region Vertices
Vector3 p0 = new Vector3( -length * .5f,    -width * .5f, height * .5f );
Vector3 p1 = new Vector3( length * .5f,     -width * .5f, height * .5f );
Vector3 p2 = new Vector3( length * .5f,     -width * .5f, -height * .5f );
Vector3 p3 = new Vector3( -length * .5f,    -width * .5f, -height * .5f );         
 
Vector3 p4 = new Vector3( -length * .5f,    width * .5f, height * .5f );
Vector3 p5 = new Vector3( length * .5f,     width * .5f, height * .5f );
Vector3 p6 = new Vector3( length * .5f,     width * .5f, -height * .5f );
Vector3 p7 = new Vector3( -length * .5f,    width * .5f, -height * .5f );
 
Vector3[] vertices = new Vector3[]
{
           //Bottom
           p0,p1, p2, p3,
 
           //Left
           p7,p4, p0, p3,
 
           //Front
           p4,p5, p1, p0,
 
           //Back
           p6,p7, p3, p2,
 
           //Right
           p5,p6, p2, p1,
 
           //Top
           p7,p6, p5, p4
};
#endregion
 
#region Normales
Vector3 up        =Vector3.up;
Vector3 down    = Vector3.down;
Vector3 front     = Vector3.forward;
Vector3 back     = Vector3.back;
Vector3 left       = Vector3.left;
Vector3 right     = Vector3.right;
 
Vector3[] normales = new Vector3[]
{
           //Bottom
           down,down, down, down,
 
           //Left
           left,left, left, left,
 
           //Front
           front,front, front, front,
 
           //Back
           back,back, back, back,
 
           //Right
           right,right, right, right,
 
           //Top
           up,up, up, up
};
#endregion      
 
#region UVs
Vector2 _00 = new Vector2( 0f, 0f );
Vector2 _10 = new Vector2( 1f, 0f );
Vector2 _01 = new Vector2( 0f, 1f );
Vector2 _11 = new Vector2( 1f, 1f );
 
Vector2[] uvs = new Vector2[]
{
           //Bottom
           _11,_01, _00, _10,
 
           //Left
           _11,_01, _00, _10,
 
           //Front
           _11,_01, _00, _10,
 
           //Back
           _11,_01, _00, _10,
 
           //Right
           _11,_01, _00, _10,
 
           //Top
           _11,_01, _00, _10,
};
#endregion
 
#region Triangles
int[] triangles = new int[]
{
           //Bottom
           3,10,
           3,21,                       
 
           //Left
           3+ 4 * 11 + 4 * 10 + 4 * 1,
           3+ 4 * 12 + 4 * 11 + 4 * 1,
 
           //Front
           3+ 4 * 21 + 4 * 20 + 4 * 2,
           3+ 4 * 22 + 4 * 21 + 4 * 2,
 
           //Back
           3+ 4 * 31 + 4 * 30 + 4 * 3,
           3+ 4 * 32 + 4 * 31 + 4 * 3,
 
           //Right
           3+ 4 * 41 + 4 * 40 + 4 * 4,
           3+ 4 * 42 + 4 * 41 + 4 * 4,
 
           //Top
           3+ 4 * 51 + 4 * 50 + 4 * 5,
           3+ 4 * 52 + 4 * 51 + 4 * 5,
 
};
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
cs



C# - Cone


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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//Note that cylinders (bottomRadius ==topRadius) and pyramids (4 sides, topRadius == 0) are types of cones, and canbe created with this script.
MeshFilter filter =gameObject.AddComponent<MeshFilter>();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float height = 1f;
float bottomRadius = .25f;
float topRadius = .05f;
int nbSides = 18;
int nbHeightSeg = 1// Not implemented yet
 
int nbVerticesCap = nbSides + 1;
#region Vertices
 
// bottom + top + sides
Vector3[] vertices = newVector3[nbVerticesCap + nbVerticesCap + nbSides * nbHeightSeg * 2 + 2];
int vert = 0;
float _2pi = Mathf.PI * 2f;
 
// Bottom cap
vertices[vert++= new Vector3(0f, 0f, 0f);
while( vert <= nbSides )
{
           floatrad = (float)vert / nbSides * _2pi;
           vertices[vert]= new Vector3(Mathf.Cos(rad) * bottomRadius, 0f, Mathf.Sin(rad) *bottomRadius);
           vert++;
}
 
// Top cap
vertices[vert++= new Vector3(0f, height,0f);
while (vert <= nbSides * 2 + 1)
{
           floatrad = (float)(vert - nbSides - 1)  /nbSides * _2pi;
           vertices[vert]= new Vector3(Mathf.Cos(rad) * topRadius, height, Mathf.Sin(rad) * topRadius);
           vert++;
}
 
// Sides
int v = 0;
while (vert <= vertices.Length - 4 )
{
           floatrad = (float)v / nbSides * _2pi;
           vertices[vert]= new Vector3(Mathf.Cos(rad) * topRadius, height, Mathf.Sin(rad) * topRadius);
           vertices[vert+ 1= new Vector3(Mathf.Cos(rad) * bottomRadius, 0, Mathf.Sin(rad) *bottomRadius);
           vert+=2;
           v++;
}
vertices[vert] = vertices[ nbSides * 2 + 2];
vertices[vert + 1= vertices[nbSides * 2 +3 ];
#endregion
 
#region Normales
 
// bottom + top + sides
Vector3[] normales = newVector3[vertices.Length];
vert = 0;
 
// Bottom cap
while( vert <= nbSides )
{
           normales[vert++]= Vector3.down;
}
 
// Top cap
while( vert <= nbSides * 2 + 1 )
{
           normales[vert++]= Vector3.up;
}
 
// Sides
= 0;
while (vert <= vertices.Length - 4 )
{                              
           floatrad = (float)v / nbSides * _2pi;
           floatcos = Mathf.Cos(rad);
           floatsin = Mathf.Sin(rad);
 
           normales[vert]= new Vector3(cos, 0f, sin);
           normales[vert+1]= normales[vert];
 
           vert+=2;
           v++;
}
normales[vert] = normales[ nbSides * 2 + 2];
normales[vert + 1= normales[nbSides * 2 +3 ];
#endregion
 
#region UVs
Vector2[] uvs = newVector2[vertices.Length];
 
// Bottom cap
int u = 0;
uvs[u++= new Vector2(0.5f, 0.5f);
while (u <= nbSides)
{
   float rad = (float)u / nbSides * _2pi;
   uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f +.5f);
   u++;
}
 
// Top cap
uvs[u++= new Vector2(0.5f, 0.5f);
while (u <= nbSides * 2 + 1)
{
   float rad = (float)u / nbSides * _2pi;
   uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f +.5f);
   u++;
}
 
// Sides
int u_sides = 0;
while (u <= uvs.Length - 4 )
{
   float t = (float)u_sides / nbSides;
   uvs[u] = new Vector3(t, 1f);
   uvs[u + 1= new Vector3(t, 0f);
    u+= 2;
   u_sides++;
}
uvs[u] = new Vector2(1f, 1f);
uvs[u + 1= new Vector2(1f, 0f);
#endregion
 
#region Triangles
int nbTriangles = nbSides + nbSides +nbSides*2;
int[] triangles = new int[nbTriangles * 3 +3];
 
// Bottom cap
int tri = 0;
int i = 0;
while (tri < nbSides - 1)
{
           triangles[i ] = 0;
           triangles[i+1 ] = tri + 1;
           triangles[i+2 ] = tri + 2;
           tri++;
           i+= 3;
}
triangles[i] = 0;
triangles[i + 1= tri + 1;
triangles[i + 2= 1;
tri++;
+= 3;
 
// Top cap
//tri++;
while (tri < nbSides*2)
{
           triangles[i ] = tri + 2;
           triangles[i+ 1= tri + 1;
           triangles[i+ 2= nbVerticesCap;
           tri++;
           i+= 3;
}
 
triangles[i] = nbVerticesCap + 1;
triangles[i + 1= tri + 1;
triangles[i + 2= nbVerticesCap;             
tri++;
+= 3;
tri++;
 
// Sides
while( tri <= nbTriangles )
{
           triangles[i ] = tri + 2;
           triangles[i+1 ] = tri + 1;
           triangles[i+2 ] = tri + 0;
           tri++;
           i+= 3;
 
           triangles[i ] = tri + 1;
           triangles[i+1 ] = tri + 2;
           triangles[i+2 ] = tri + 0;
           tri++;
           i+= 3;
}
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
cs


C# - Tube

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
MeshFilter filter =gameObject.AddComponent<MeshFilter>();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float height = 1f;
int nbSides = 24;
 
// Outter shell is at radius1 + radius2 /2, inner shell at radius1 - radius2 / 2
float bottomRadius1 = .5f;
float bottomRadius2 = .15f;
float topRadius1 = .5f;
float topRadius2 = .15f;
 
int nbVerticesCap = nbSides * 2 + 2;
int nbVerticesSides = nbSides * 2 + 2;
#region Vertices
 
// bottom + top + sides
Vector3[] vertices = newVector3[nbVerticesCap * 2 + nbVerticesSides * 2];
int vert = 0;
float _2pi = Mathf.PI * 2f;
 
// Bottom cap
int sideCounter = 0;
while( vert < nbVerticesCap )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
           floatcos = Mathf.Cos(r1);
           floatsin = Mathf.Sin(r1);
           vertices[vert]= new Vector3( cos * (bottomRadius1 - bottomRadius2 * .5f), 0f, sin * (bottomRadius1- bottomRadius2 * .5f));
           vertices[vert+1]= new Vector3( cos * (bottomRadius1 + bottomRadius2 * .5f), 0f, sin *(bottomRadius1 + bottomRadius2 * .5f));
           vert+= 2;
}
 
// Top cap
sideCounter = 0;
while( vert < nbVerticesCap * 2 )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
           floatcos = Mathf.Cos(r1);
           floatsin = Mathf.Sin(r1);
           vertices[vert]= new Vector3( cos * (topRadius1 - topRadius2 * .5f), height, sin * (topRadius1- topRadius2 * .5f));
           vertices[vert+1]= new Vector3( cos * (topRadius1 + topRadius2 * .5f), height, sin * (topRadius1+ topRadius2 * .5f));
           vert+= 2;
}
 
// Sides (out)
sideCounter = 0;
while (vert < nbVerticesCap * 2 +nbVerticesSides )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
           floatcos = Mathf.Cos(r1);
           floatsin = Mathf.Sin(r1);
 
           vertices[vert]= new Vector3(cos * (topRadius1 + topRadius2 * .5f), height, sin * (topRadius1+ topRadius2 * .5f));
           vertices[vert+ 1= new Vector3(cos * (bottomRadius1 + bottomRadius2 * .5f), 0, sin *(bottomRadius1 + bottomRadius2 * .5f));
           vert+=2;
}
 
// Sides (in)
sideCounter = 0;
while (vert < vertices.Length )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
           floatcos = Mathf.Cos(r1);
           floatsin = Mathf.Sin(r1);
 
           vertices[vert]= new Vector3(cos * (topRadius1 - topRadius2 * .5f), height, sin * (topRadius1- topRadius2 * .5f));
           vertices[vert+ 1= new Vector3(cos * (bottomRadius1 - bottomRadius2 * .5f), 0, sin *(bottomRadius1 - bottomRadius2 * .5f));
           vert+= 2;
}
#endregion
 
#region Normales
 
// bottom + top + sides
Vector3[] normales = newVector3[vertices.Length];
vert = 0;
 
// Bottom cap
while( vert < nbVerticesCap )
{
           normales[vert++]= Vector3.down;
}
 
// Top cap
while( vert < nbVerticesCap * 2 )
{
           normales[vert++]= Vector3.up;
}
 
// Sides (out)
sideCounter = 0;
while (vert < nbVerticesCap * 2 +nbVerticesSides )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
 
           normales[vert]= new Vector3(Mathf.Cos(r1), 0f, Mathf.Sin(r1));
           normales[vert+1]= normales[vert];
           vert+=2;
}
 
// Sides (in)
sideCounter = 0;
while (vert < vertices.Length )
{
           sideCounter= sideCounter == nbSides ? 0 : sideCounter;
 
           floatr1 = (float)(sideCounter++/ nbSides * _2pi;
 
           normales[vert]= -(new Vector3(Mathf.Cos(r1), 0f, Mathf.Sin(r1)));
           normales[vert+1]= normales[vert];
           vert+=2;
}
#endregion
 
#region UVs
Vector2[] uvs = newVector2[vertices.Length];
 
vert = 0;
// Bottom cap
sideCounter = 0;
while( vert < nbVerticesCap )
{
           floatt = (float)(sideCounter++/ nbSides;
           uvs[vert++ ] = new Vector2( 0f, t );
           uvs[vert++ ] = new Vector2( 1f, t );
}
 
// Top cap
sideCounter = 0;
while( vert < nbVerticesCap * 2 )
{
           floatt = (float)(sideCounter++/ nbSides;
           uvs[vert++ ] = new Vector2( 0f, t );
           uvs[vert++ ] = new Vector2( 1f, t );
}
 
// Sides (out)
sideCounter = 0;
while (vert < nbVerticesCap * 2 +nbVerticesSides )
{
           floatt = (float)(sideCounter++/ nbSides;
           uvs[vert++ ] = new Vector2( t, 0f );
           uvs[vert++ ] = new Vector2( t, 1f );
}
 
// Sides (in)
sideCounter = 0;
while (vert < vertices.Length )
{
           floatt = (float)(sideCounter++/ nbSides;
           uvs[vert++ ] = new Vector2( t, 0f );
           uvs[vert++ ] = new Vector2( t, 1f );
}
#endregion
 
#region Triangles
int nbFace = nbSides * 4;
int nbTriangles = nbFace * 2;
int nbIndexes = nbTriangles * 3;
int[] triangles = new int[nbIndexes];
 
// Bottom cap
int i = 0;
sideCounter = 0;
while (sideCounter < nbSides)
{
           intcurrent = sideCounter * 2;
           intnext = sideCounter * 2 + 2;
 
           triangles[i++ ] = next + 1;
           triangles[i++ ] = next;
           triangles[i++ ] = current;
 
           triangles[i++ ] = current + 1;
           triangles[i++ ] = next + 1;
           triangles[i++ ] = current;
 
           sideCounter++;
}
 
// Top cap
while (sideCounter < nbSides * 2)
{
           intcurrent = sideCounter * 2 + 2;
           intnext = sideCounter * 2 + 4;
 
           triangles[i++ ] = current;
           triangles[i++ ] = next;
           triangles[i++ ] = next + 1;
 
           triangles[i++ ] = current;
           triangles[i++ ] = next + 1;
           triangles[i++ ] = current + 1;
 
           sideCounter++;
}
 
// Sides (out)
while( sideCounter < nbSides * 3 )
{
           intcurrent = sideCounter * 2 + 4;
           intnext = sideCounter * 2 + 6;
 
           triangles[i++ ] = current;
           triangles[i++ ] = next;
           triangles[i++ ] = next + 1;
 
           triangles[i++ ] = current;
           triangles[i++ ] = next + 1;
           triangles[i++ ] = current + 1;
 
           sideCounter++;
}
 
 
// Sides (in)
while( sideCounter < nbSides * 4 )
{
           intcurrent = sideCounter * 2 + 6;
           intnext = sideCounter * 2 + 8;
 
           triangles[i++ ] = next + 1;
           triangles[i++ ] = next;
           triangles[i++ ] = current;
 
           triangles[i++ ] = current + 1;
           triangles[i++ ] = next + 1;
           triangles[i++ ] = current;
 
           sideCounter++;
}
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
cs


C# - Torus



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
MeshFilter filter =gameObject.AddComponent< MeshFilter >();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float radius1 = 1f;
float radius2 = .3f;
int nbRadSeg = 24;
int nbSides = 18;
 
#region Vertices           
Vector3[] vertices = newVector3[(nbRadSeg+1* (nbSides+1)];
float _2pi = Mathf.PI * 2f;
forint seg = 0; seg <= nbRadSeg; seg++)
{
           intcurrSeg = seg  == nbRadSeg ? 0 : seg;
 
           floatt1 = (float)currSeg / nbRadSeg * _2pi;
           Vector3r1 = new Vector3( Mathf.Cos(t1) * radius1, 0f, Mathf.Sin(t1) * radius1 );
 
           for(int side = 0; side <= nbSides; side++ )
           {
                     intcurrSide = side == nbSides ? 0 : side;
 
                     Vector3normale = Vector3.Cross( r1, Vector3.up );
                     floatt2 = (float)currSide / nbSides * _2pi;
                     Vector3r2 = Quaternion.AngleAxis( -t1 * Mathf.Rad2Deg, Vector3.up ) *new Vector3(Mathf.Sin(t2) * radius2, Mathf.Cos(t2) * radius2 );
 
                     vertices[side+ seg * (nbSides+1)] = r1 + r2;
           }
}
#endregion
 
#region Normales                    
Vector3[] normales = newVector3[vertices.Length];
forint seg = 0; seg <= nbRadSeg; seg++)
{
           intcurrSeg = seg  == nbRadSeg ? 0 : seg;
 
           floatt1 = (float)currSeg / nbRadSeg * _2pi;
           Vector3r1 = new Vector3( Mathf.Cos(t1) * radius1, 0f, Mathf.Sin(t1) * radius1 );
 
           for(int side = 0; side <= nbSides; side++ )
           {
                     normales[side+ seg * (nbSides+1)] = (vertices[side + seg * (nbSides+1)] - r1).normalized;
           }
}
#endregion
 
#region UVs
Vector2[] uvs = newVector2[vertices.Length];
forint seg = 0; seg <= nbRadSeg; seg++)
           for(int side = 0; side <= nbSides; side++ )
                     uvs[side+ seg * (nbSides+1)] = new Vector2( (float)seg / nbRadSeg, (float)side /nbSides );
#endregion
 
#region Triangles
int nbFaces = vertices.Length;
int nbTriangles = nbFaces * 2;
int nbIndexes = nbTriangles * 3;
int[] triangles = new int[ nbIndexes ];
 
int i = 0;
forint seg = 0; seg <= nbRadSeg; seg++)
{                              
           for(int side = 0; side <= nbSides - 1; side++ )
           {
                     intcurrent = side + seg * (nbSides+1);
                     intnext = side + (seg < (nbRadSeg) ?(seg+1* (nbSides+1) : 0);
 
                     if(i < triangles.Length - 6 )
                     {
                                triangles[i++]= current;
                                triangles[i++]= next;
                                triangles[i++]= next+1;
 
                                triangles[i++]= current;
                                triangles[i++]= next+1;
                                triangles[i++]= current+1;
                     }
           }
}
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
cs


C# - Sphere

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
97
98
99
//Regular sphere. Source :http://stackoverflow.com/questions/4081898/procedurally-generate-a-sphere-mesh
MeshFilter filter =gameObject.AddComponent< MeshFilter >();
Mesh mesh = filter.mesh;
mesh.Clear();
 
float radius = 1f;
// Longitude |||
int nbLong = 24;
// Latitude ---
int nbLat = 16;
 
#region Vertices
Vector3[] vertices = new Vector3[(nbLong+1)* nbLat + 2];
float _pi = Mathf.PI;
float _2pi = _pi * 2f;
 
vertices[0= Vector3.up * radius;
forint lat = 0; lat < nbLat; lat++ )
{
           floata1 = _pi * (float)(lat+1/ (nbLat+1);
           floatsin1 = Mathf.Sin(a1);
           floatcos1 = Mathf.Cos(a1);
 
           for(int lon = 0; lon <= nbLong; lon++ )
           {
                     floata2 = _2pi * (float)(lon == nbLong ? 0 : lon) / nbLong;
                     floatsin2 = Mathf.Sin(a2);
                     floatcos2 = Mathf.Cos(a2);
 
                     vertices[lon + lat * (nbLong + 1+ 1= new Vector3( sin1 * cos2, cos1, sin1 * sin2 ) *radius;
           }
}
vertices[vertices.Length-1= Vector3.up *-radius;
#endregion
 
#region Normales                    
Vector3[] normales = newVector3[vertices.Length];
forint n = 0; n < vertices.Length; n++)
           normales[n]= vertices[n].normalized;
#endregion
 
#region UVs
Vector2[] uvs = newVector2[vertices.Length];
uvs[0= Vector2.up;
uvs[uvs.Length-1= Vector2.zero;
forint lat = 0; lat < nbLat; lat++ )
           for(int lon = 0; lon <= nbLong; lon++ )
                     uvs[lon+ lat * (nbLong + 1+ 1= new Vector2( (float)lon / nbLong, 1f -(float)(lat+1/ (nbLat+1) );
#endregion
 
#region Triangles
int nbFaces = vertices.Length;
int nbTriangles = nbFaces * 2;
int nbIndexes = nbTriangles * 3;
int[] triangles = new int[ nbIndexes ];
 
//Top Cap
int i = 0;
forint lon = 0; lon < nbLong; lon++ )
{
           triangles[i++]= lon+2;
           triangles[i++]= lon+1;
           triangles[i++]= 0;
}
 
//Middle
forint lat = 0; lat < nbLat - 1; lat++)
{
           for(int lon = 0; lon < nbLong; lon++ )
           {
                     intcurrent = lon + lat * (nbLong + 1+ 1;
                     intnext = current + nbLong + 1;
 
                     triangles[i++]= current;
                     triangles[i++]= current + 1;
                     triangles[i++]= next + 1;
 
                     triangles[i++]= current;
                     triangles[i++]= next + 1;
                     triangles[i++]= next;
           }
}
 
//Bottom Cap
forint lon = 0; lon < nbLong; lon++ )
{
           triangles[i++]= vertices.Length - 1;
           triangles[i++]= vertices.Length - (lon+2- 1;
           triangles[i++]= vertices.Length - (lon+1- 1;
}
#endregion
 
mesh.vertices = vertices;
mesh.normals = normales;
mesh.uv = uvs;
mesh.triangles = triangles;
 
mesh.RecalculateBounds();
mesh.Optimize();
cs


C# - IsoSphere


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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//This is a sphere without poles. Source :http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html
//Note : Don't forget to includeSystem.Collections.Generic. And there is no UV yet, not sure how to go about itactually.
private static class IsoSphere
{
   private struct TriangleIndices
    {
       public int v1;
       public int v2;
       public int v3;
 
       public TriangleIndices(int v1, int v2, int v3)
       {
           this.v1 = v1;
           this.v2 = v2;
           this.v3 = v3;
       }
    }
 
   // return index of point in the middle of p1 and p2
   private static int getMiddlePoint(int p1, int p2, refList<Vector3> vertices, ref Dictionary<longint> cache, floatradius)
    {
       // first check if we have it already
       bool firstIsSmaller = p1 < p2;
       long smallerIndex = firstIsSmaller ? p1 : p2;
       long greaterIndex = firstIsSmaller ? p2 : p1;
       long key = (smallerIndex << 32+ greaterIndex;
 
       int ret;
       if (cache.TryGetValue(key, out ret))
       {
           return ret;
       }
 
       // not in cache, calculate it
       Vector3 point1 = vertices[p1];
       Vector3 point2 = vertices[p2];
       Vector3 middle = new Vector3
                     (
           (point1.x + point2.x) / 2f,
           (point1.y + point2.y) / 2f,
           (point1.z + point2.z) / 2f
                     );
 
       // add vertex makes sure point is on unit sphere
                     inti = vertices.Count;
       vertices.Add( middle.normalized * radius );
 
       // store it, return index
       cache.Add(key, i);
 
       return i;
    }
 
   public static void Create()
    {
       MeshFilter filter = gameObject.AddComponent< MeshFilter >();
       Mesh mesh = filter.mesh;
       mesh.Clear();
 
       List<Vector3> vertList = new List<Vector3>();
       Dictionary<longint> middlePointIndexCache = new Dictionary<long,int>();
       int index = 0;
 
       int recursionLevel = 3;
       float radius = 1f;
 
       // create 12 vertices of a icosahedron
       float t = (1f + Mathf.Sqrt(5f)) / 2f;
 
       vertList.Add(new Vector3(-1f, t,  0f).normalized * radius);
       vertList.Add(new Vector3( 1f, t,  0f).normalized * radius);
       vertList.Add(new Vector3(-1f, -t, 0f).normalized * radius);
       vertList.Add(new Vector3( 1f, -t, 0f).normalized * radius);
 
       vertList.Add(new Vector3( 0f, -1f, t).normalized * radius);
       vertList.Add(new Vector3( 0f, 1f,  t).normalized * radius);
       vertList.Add(new Vector3( 0f, -1f, -t).normalized * radius);
       vertList.Add(new Vector3( 0f,  1f,-t).normalized * radius);
 
       vertList.Add(new Vector3( t,  0f,-1f).normalized * radius);
       vertList.Add(new Vector3( t, 0f,  1f).normalized * radius);
       vertList.Add(new Vector3(-t,  0f,-1f).normalized * radius);
        vertList.Add(new Vector3(-t,  0f, 1f).normalized * radius);
 
 
       // create 20 triangles of the icosahedron
       List<TriangleIndices> faces = new List<TriangleIndices>();
 
       // 5 faces around point 0
       faces.Add(new TriangleIndices(0115));
       faces.Add(new TriangleIndices(051));
       faces.Add(new TriangleIndices(017));
       faces.Add(new TriangleIndices(0710));
       faces.Add(new TriangleIndices(01011));
 
       // 5 adjacent faces
       faces.Add(new TriangleIndices(159));
       faces.Add(new TriangleIndices(5114));
       faces.Add(new TriangleIndices(11102));
       faces.Add(new TriangleIndices(1076));
       faces.Add(new TriangleIndices(718));
 
        // 5 faces around point 3
       faces.Add(new TriangleIndices(394));
       faces.Add(new TriangleIndices(342));
       faces.Add(new TriangleIndices(326));
       faces.Add(new TriangleIndices(368));
       faces.Add(new TriangleIndices(389));
 
       // 5 adjacent faces
       faces.Add(new TriangleIndices(495));
       faces.Add(new TriangleIndices(2411));
       faces.Add(new TriangleIndices(6210));
       faces.Add(new TriangleIndices(867));
       faces.Add(new TriangleIndices(981));
 
 
       // refine triangles
       for (int i = 0; i < recursionLevel; i++)
       {
           List<TriangleIndices> faces2 = new List<TriangleIndices>();
           foreach (var tri in faces)
           {
                // replace triangle by 4triangles
                int a = getMiddlePoint(tri.v1,tri.v2, ref vertList, ref middlePointIndexCache, radius);
                int b = getMiddlePoint(tri.v2,tri.v3, ref vertList, ref middlePointIndexCache, radius);
                int c = getMiddlePoint(tri.v3,tri.v1, ref vertList, ref middlePointIndexCache, radius);
 
                faces2.Add(newTriangleIndices(tri.v1, a, c));
                faces2.Add(newTriangleIndices(tri.v2, b, a));
                faces2.Add(newTriangleIndices(tri.v3, c, b));
                faces2.Add(newTriangleIndices(a, b, c));
           }
           faces = faces2;
       }
 
       mesh.vertices = vertList.ToArray();
 
       List< int > triList = new List<int>();
       forint i = 0; i <faces.Count; i++ )
       {
           triList.Add( faces[i].v1 );
           triList.Add( faces[i].v2 );
           triList.Add( faces[i].v3 );
       }                    
       mesh.triangles = triList.ToArray();
       mesh.uv = new Vector2[ vertices.Length ];
 
       Vector3[] normales = new Vector3[ vertList.Count];
       forint i = 0; i < normales.Length; i++ )
           normales[i] = vertList[i].normalized;
 
 
       mesh.normals = normales;
 
       mesh.RecalculateBounds();
       mesh.Optimize();
    }
}
cs


Posted by 시리시안