C# unity3d 貪吃蛇 游戲 源碼 及其感想


 

這個游戲的設計過程是這樣的:

1,創建 🐍的身體,在 u3d里我只是用一個小方塊表示 設計好蛇頭后就添加meterial 這樣蛇的基本元素都有了

 

2,創建地圖,在這個項目里,我是使用一個 3d projiect 叫做 Quad的對象。然后要將地圖大小改變為50,50.就是將該對象的scale改為50,50,1

 

3,創建食物,也是新建一個小方塊,在tag那里添加新標簽,填為 Food

 

4,創建body,還是一個小方塊, 在tag那里添加新標簽,填為 Body

方法上難點

1.觸發器的使用,記住 OnTriggerEnter的使用,前提是兩個碰撞的對象,必須其一個有rigidbody剛體組件,然后其中一個(不是另外一個 是兩個中的一個)必須要勾上Is Trigger,兩個不沖突,就可以了。設計碰撞器的大小,也是個細活。

在這里我只是使用了 Box Collider的組件,在完成路上曾經將🐍的Is Trigger打開,所以跟地圖Quad沖突了,所以導致不斷刷新這個場景。

2.一個方法  叫做 other.gameObject.CompareTag ("Food"),我在OnTriggerEnter里的主要部分。

檢測是否碰到一個Tag是否為Food的對象,然后檢測到就將其刪除,並延伸自己的身體。在后面后幾次開發中都使用到,是個很重要的方法。

具體使用方法為

C# ⇒ bool CompareTag(string tag);

Is this game object tagged with /tag/?

3.蛇的身體的移動,見到概括 就是當蛇 吃到食物后,在下一幀中延長了身體.蛇的身體是保存在一個集合中去的,還有最重要的一點!就是 

用一個Vector3 VPosition記錄蛇在移動前的位置,然后移動蛇,在原地生成一個body,位置為VPosition,然后lis.Insert(0,g)//g為body那個對象

((GameObject)list[list.Count-1]).transform.position = VPostion;//這句則是將當前集合最后一個元素賦值為VPosition

list.Insert (0, list [list.Count - 1]);//然后在集合的0位置插入最后一個元素

這樣的話,g就排到了集合的第二個,而最后一個元素排到了第一個,

list.RemoveAt (list.Count-1);

然后刪除集中中最后的元素,整個蛇移動的過程 和吃食物生成蛇的過程就清晰了。

代碼最后 還有兩段小UI,就不放上來了。

第一次記錄自己的u3d開發過程,以后有經驗后,應該不會這樣全部詳細保留下來了,主要供自己學習使用,代碼未優化,只是達到實現效果而已。

==================================究極無敵華麗分界線==================================using UnityEngine;

using System.Collections;
using System.Diagnostics;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
public class SnakeMove : MonoBehaviour {
    List<Transform> Body = new List<Transform> ();//Transform的表
    public GameObject BodyObject;
    public GameObject sFood;
    //updown Y軸 left down是x軸  forward back是z 軸
    Vector3 postion = Vector3.up;
    private bool s = false;
    // Use this for initialization
    public float speed=0.1f;
    public float time = 0;
    //public float time0 =1;
//    public float xlimit = 25.5f;
//    public float ylimit = 25.5f;
    public int xlimit = 25;
    public int ylimit = 25;
    //傷害數值
    public int Value;
    //目標位置
    private Vector3 mTarget;
    //屏幕坐標
    private Vector3 mScreen;
    //文本寬度
    public float ContentWidth = 100;
    //文本高度
    public float ContentHeight = 50;
    //GUI坐標
    private Vector2 mPoint;
    //炫酷的字體
    GUIStyle frontStyle = new GUIStyle();

    public Text text;
    Vector3 VPostion;

    public GameObject body1;
    public ArrayList list = new ArrayList();
    private bool isEated = false;
    void Start () {
        
        //Time.timeScale=1;
        //time = Time.time + time;
        //InvokeRepeating 從第一秒開始,每隔四秒調用一次
        InvokeRepeating ("Food", 1, 4);
        InvokeRepeating ("Move", speed, speed);

        //獲取目標位置
        mTarget =transform.position;
        //獲取屏幕坐標
        mScreen =Camera.main.WorldToScreenPoint(mTarget);
        //將屏幕坐標轉化為GUI坐標
        mPoint = new Vector2(mScreen.x,Screen.height-mScreen.y);
        //
        Value =0;
    }
    
    // Update is called once per frame
    void Update () {

        if(Input.GetMouseButtonDown(0))
            Time.timeScale=1;
        if (Input.GetKeyDown (KeyCode.D)&&postion!=Vector3.left) 
        {
            postion = Vector3.right;
        }
        if (Input.GetKeyDown (KeyCode.A)&&postion!=Vector3.right) 
        {
            postion = Vector3.left;
        }
        if (Input.GetKeyDown (KeyCode.S)&&postion!=Vector3.up) 
        {
            postion = Vector3.down;
        }
        if (Input.GetKeyDown (KeyCode.W)&&postion!=Vector3.down) 
        {
            postion = Vector3.up;
        }
        //Time.tiem 系統時間
//        if (time<=Time.time) 
//        {
//            transform.Translate (postion);
//            time += 1;
//            //time 越小 速度越快
//        }

        //Random r = new Random ();
        //OnTriggerEnter();
    
    }
    void Move()
    {
        //transform.Translate (postion);

        VPostion = transform.position;
        transform.Translate (postion); //Transform.Translate平移 向某方向移動物體多少距離
        if (isEated) 
        {
            GameObject g = (GameObject)Instantiate(body1,VPostion,Quaternion.identity);
            g.GetComponent<MeshRenderer> ().material.color = new Color (Random.Range (0, 1.0f), Random.Range (0, 1.0f), Random.Range (0, 1.0f));
            list.Insert (0, g);//將一個項插入指定索引處的 IList<(Of <(T>)>)。 
                                         //將元素插入 ArrayList 的指定索引處。 可在任意位置插入。
            isEated = false;
        }
        else if (list.Count>0)
        {
            //            //最后一個元素的位置賦值給新的位置
            //            //最后一個元素插入在第一個元素地址
            //            //刪除最后一個元素
            ((GameObject)list[list.Count-1]).transform.position = VPostion;
            list.Insert (0, list [list.Count - 1]);//在0的位置插入一個
            list.RemoveAt (list.Count-1);//移除 ArrayList 的指定索引處的元素。
        }
    }
    void Food()
    {
        System.Random r = new System.Random ();
        float x = r.Next (-xlimit,xlimit);
        float y = r.Next (-ylimit,ylimit);

//        float x = Random.Range(-xlimit,xlimit);
//        float y = Random.Range (-ylimit, ylimit);
        Instantiate (sFood, new Vector2 (x, y), Quaternion.identity);
    }
    void OnTriggerEnter(Collider other)
    {
   
        if (other.gameObject.CompareTag ("Food")) 
        {
            if(!isEated)
                Value++;
            isEated = true;
            Destroy (other.gameObject);
        }
        else 
        {
            

            Time.timeScale=0;

            SceneManager.LoadScene (0);
        }
        text.text = "Score :" + Value;
    }
    void OnGUI()
    {
        //保證目標在攝像機前方
        if (mScreen.z > 0) 
        {
            //GUI.color = Color.blue;
            //內部使用GUI坐標進行繪制
            frontStyle.fontSize=40;
            frontStyle.normal.background = null;//設置背景填充
            frontStyle.normal.textColor = new Color (100, 0, 128);//設置字體顏色
            GUI.Label(new Rect(30,0,ContentWidth,ContentHeight),"分數為"+Value.ToString(),frontStyle);
            //                  mPoint.x,mPoint.y
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM