边玩边学之3D打箱子

来源:互联网 发布:mac可以玩什么网络游戏 编辑:程序博客网 时间:2024/05/01 14:22

demo效果图:


目标:在3D场景下设置一排箱子,点击后发射弹球,碰撞后改变轨迹

主要标记:

1.场景的搭建,熟悉3d场景的xyz坐标系,create放置箱子的地板plane,在上面创建一面摞在一起的的箱子并设置箱子的属性:

for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++){GameObject obj = GameObject.CreatePrimitive (PrimitiveType.Cube);obj.transform.position = new Vector3 (i, j, -1);obj.GetComponent<Renderer>().material = BoxMaterial;obj.AddComponent<Rigidbody> ();obj.AddComponent<AutoDestroy> ();}}
2.设置鼠标按下时的触发事件,这里给了球体Rigidbody,通过AddForce计算弹出的距离:

void Update () {if (Input.GetMouseButtonDown(0)) {GameObject ball = GameObject.CreatePrimitive (PrimitiveType.Sphere);ball.transform.position = Camera.main.transform.position;ball.GetComponent<Renderer> ().material = BulletMaterial;ball.AddComponent<Rigidbody> ();ball.AddComponent<AutoDestroy> ();objPlane.GetComponent<AudioSource> ().Play ();Vector3 tagetPos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 3));ball.GetComponent<Rigidbody> ().AddForce ((tagetPos-Camera.main.transform.position)*10, ForceMode.Impulse);}}
3.OnGUI绘制界面,设置了ShotBox title:

void OnGUI(){GUILayout.Label ("ShotBox");}
4.object的释放,需要把不需要或不在视野内的球体和方块释放,以防内存的增加以及不必要开销:

void OnBecameInvisible (){Destroy (this.gameObject);}
5.绘制瞄准星,在导入图片后通过Texture来设置和引用:

void OnGUI (){//图片坐标左上角开始float left = Input.mousePosition.x - 30;//屏幕坐标左下角开始float top = Screen.height - Input.mousePosition.y - 30;//GUI.DrawTexture (new Rect (0, 15, CursorTexture.width, CursorTexture.height), CursorTexture);//GUI.DrawTexture (new Rect (0, 15, 60, 60), CursorTexture);GUI.DrawTexture(new Rect(left, top, 60, 60), CursorTexture);}

------------------------------------------------------我是分界线------------------------------------------------------

可借鉴学习路线:

1.C#、.net基础

2.GUI、NGUI、2DToolKit

3.3D控制、物理引擎、角色控制

4.粒子系统、音频

5.iOS、Android开发相关基础

6.Socket、Http通讯、服务器开发


1 0