c#和unity引擎的全部筆記

Shader攝像機死亡效果

做者: 1056923207@qq.com
1:Shader腳本
 
Shader  "Custom/CameraShader"
{
     Properties
    {
        _MainTex(  "MainTexture",2D )= "white" {}
    }
     SubShader
    {
     Tags{"RenderType"= "Opaque"}
     LOD 200
     Pass
    {  
     CGPROGRAM
     #pragma vertex vert
     #pragma fragment frag
     #include "UnityCG.cginc"  
     sampler2D _MainTex;
     void vert ( inout appdata_base v)
    {
    v.vertex= mul ( UNITY_MATRIX_MVP ,v.vertex);
    }
     float4 frag( appdata_base v):COLOR
    {
     fixed4 c= tex2D(_MainTex,v.texcoord);
     fixed d = 0.3*c.r+0.59*c.g+0.11*c.b;
     return fixed4 (d,d,d,1); 
    }                 
     ENDCG           
    }
}
}
 
 
2:攝像機上掛載的腳本:
 
using  UnityEngine;
using  System.Collections;
 
public  class CameraTest : MonoBehaviour {
 
     public Material material;
     //相機的回調函數
     void OnRenderImage( RenderTexture rest/*相機渲染的圖像*/ , RenderTexture dest /*通過Shader渲染後的圖像*/ )
    {
         Graphics.Blit(rest, dest, material);//攝像機渲染好的圖像通過處理再顯示出來
    }
}
 

 

快速排序

做者: 1056923207@qq.com
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
 
namespace  QuickSort
{
     class Program
    {
         static void Main(string[] args)
        {
             int[] arr = new int[8000000];
             for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = 8000000 - i;
            }
             kuaisu(arr, 0, arr.Length - 1);
             //BuddleSort(arr);
             foreach (var item in arr)
            {
                 Console.WriteLine(item);
            }
        }
         //普通冒泡排序
         public static void BuddleSort( int[] arr)
        {
             for (int i = 0; i < arr.Length-1; i++)
            {
                 for (int j = 0; j < arr.Length-1-i; j++)
                {
                     if (arr[j]>arr[j+1])
                    {
                         int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
 
                    }
                }
 
            }
 
        }
 
         //快速排序
         public static void kuaisu( int [] arr,int left,int right)
        {
             if (left>=right)
            {
                 return;
            }
             if (left<right)
            {
                 int middle = arr[(left + right) / 2];
                 int i = left-1;
                 int j = right+1;
                 while (true )
                {
                     while (arr[++i] < middle) { }
                     while (arr[--j] > middle) { }
                     if (i>=j)
                    {
                         break;
                    }
                     int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;                  
                }
                kuaisu(arr, left, i - 1);
                kuaisu(arr, j + 1, right);
            }
        }
    }
}

 

Shader

來源網址: http://www.jianshu.com/p/7b9498e58659
做者: 1056923207@qq.com
 
最他媽好的解釋  沒有之一
 
 
 
 
 
 
 
 
 
 
struct SurfaceOutput {
  half3 Albedo; // 紋理顏色值(r, g, b)
  half3 Normal; // 法向量(x, y, z)
  half3 Emission; // 自發光顏色值(r, g, b)
  half Specular; // 鏡面反射度
  half Gloss; // 光澤度
  half Alpha; // 不透明度
};
 
 
 
ambient 環境光

 

Shader

做者: 1056923207@qq.com
shader數據類型
fixed 取值範圍[-2,2]
half
double

 

網絡

做者: 1056923207@qq.com
同步動畫  在人物身上綁定來性格組件:networkidentity,

 

Out和Ref的區別

來源網址: http://www.cnblogs.com/sjrhero/articles/1922902.html
做者: 1056923207@qq.com

out的使用php

————————————————————————————————————————————————— html

   class Program
    {
        static void Main(string[] args)
        {node

     string tmp;    //先聲明,但不初始化算法

     User _user=new User();      sql

     _user.Name(out tmp);        //調用Name方法數據庫

              Console.WriteLine("{0}",tmp); //這時tmp的值爲「在這裏面賦值了」編程

              Console.ReadKey(true);json

   }canvas

     }小程序

  class User

      {

    public void Name(out string tmps)

           {

       tmps="在這裏面賦值了";

           }

      }

       結果:

              在這裏面賦值了

—————————————————————————————————————————————————

 ref的使用

—————————————————————————————————————————————————

 

   class Program
    {
        static void Main(string[] args)
        {

     string tmp="傳值以前";    //聲明並初始化        這時若是輸出tmp值爲"傳值以前"

          User _user=new User();

              _user.Name(ref tmp);

              Console.WriteLine("{0}",tmp);

              Console.ReadKey(true);

        }

    }

    class User

    {

         public void Name(ref string tmps)

         {

              tmps="傳值以後";

         }

    }

    結果:

          傳值以後

—————————————————————————————————————————————————

區別:

ref和out的區別在C# 中,既能夠經過值也能夠經過引用傳遞參數。經過引用傳遞參數容許函數成員更改參數的值,並保持該更改。若要經過引用傳遞參數, 可以使用ref或out關鍵字。ref和out這兩個關鍵字都可以提供類似的功效,其做用也很像C中的指針變量。它們的區別是:

一、使用ref型參數時,傳入的參數必須先被初始化。對out而言,必須在方法中對其完成初始化。

二、使用ref和out時,在方法的參數和執行方法時,都要加Ref或Out關鍵字。以知足匹配。

三、out適合用在須要retrun多個返回值的地方,而ref則用在須要被調用的方法修改調用者的引用的時候。

out

方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變量。當控制傳遞迴調用方法時,在方法中對參數所作的任何更改都將反映在該變量中。

當但願方法返回多個值時,聲明 out 方法很是有用。使用 out 參數的方法仍然能夠返回一個值。一個方法能夠有一個以上的 out 參數。

若要使用 out 參數,必須將參數做爲 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。

沒必要初始化做爲 out 參數傳遞的變量。然而,必須在方法返回以前爲 out 參數賦值。

屬性不是變量,不能做爲 out 參數傳遞。

 

 
ref是    有進有出,而out是       只出不進。

 

根據Txt文件數據生成地圖

做者: 1056923207@qq.com
往文件寫東西用:FileStream;
從文件讀東西用:StreamReader;
 
字符串轉化爲字節的區別:
 一個一個轉換:      this .data[i, j] =  byte .Parse(data[i][j].ToString());
多個轉換                                   byte [] map =  Encoding .UTF8.GetBytes(sb.ToString());//想獲得什麼類型的數據就Get什麼
 
 
 
 
 
using  UnityEngine;
using  System.Collections;
using  UnityEditor;
using  System.IO;
using  System.Text;
 
 
public  class MapBuilder : Editor{
 
     public const int RowCount = 6;
     public const int ColCount = 6;
 
 
    [ MenuItem (  "Map/Build")]
     static void BuildMap()
    {      
         //建立地圖10*10
         //規則:藍色是海洋,紅色是障礙物,黃色是終止點
         byte[,] map = GetMapData();
         GameObject Roads = new GameObject( "Roads");
         GameObject BlueCube = Resources .Load("Blue") as GameObject ;
         GameObject RedCude = Resources .Load("Red") as GameObject ;
         for (int i = 0; i <RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {              
                 switch (map[i,j])
                {
                     case 1:
                       GameObject RCube= Instantiate(RedCude) as GameObject;
                        RCube.transform.SetParent(Roads.transform);
                        RCube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f );
                        RCube.transform.localScale =  Vector3.one * 0.8f;
                        RCube.name = i.ToString() +  "_" + j.ToString();
                         break;
                     case 2:
                        GameObject Bcube= Instantiate(BlueCube) as GameObject;
                        Bcube.transform.SetParent(Roads.transform);
                        Bcube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f );
                        Bcube.transform.localScale =  Vector3.one * 0.8f;
                        Bcube.name = i.ToString() +  "_" + j.ToString();               
                         break;
                     default:
                       GameObject cube=  GameObject .CreatePrimitive(PrimitiveType.Cube);
                        cube.transform.SetParent(Roads.transform);
                        cube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f);
                        cube.transform.localScale =  Vector3.one * 0.8f;
                        cube.name = i.ToString() +  "_" + j.ToString();
                         break;
                }
            }
        }
    }
     //從地圖取數據
    [ MenuItem (  "Map/Test")]
     static byte[,] GetMapData()
    {
         string path = Application .dataPath + "/Map/Map1.txt";
         //文件讀寫流
         StreamReader sr = new StreamReader(path); //讀取文件而且將文件中的內容放到sr中      
         string result = sr.ReadToEnd(); //讀取內容(從當前位置到末尾讀取)       
         string[] data = result.Split(new char[] { '\n'});//逐行截取,生成的數據就是一行一行的
         byte[,] mapdata = new byte[RowCount, ColCount]; //定義一個二維數組
         Debug.Log(data.Length);
         for (int i = 0; i < RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
                mapdata[i, j] =  byte.Parse(data[i][j].ToString());//將字符串存入到二維數組
            }
        }
         return mapdata;
    }
 
     //往地圖寫數據
    [ MenuItem (  "Map/CreateMap")]
     static void CreateMap()
    {
         //第一步訪問txt文件
         string path = Application .dataPath + "/Map/Map1.txt";
         FileStream fs= File .OpenWrite(path);//能夠對文件進行操做      
         //第二步填充內容
         StringBuilder sb = new StringBuilder(); //容量可變的字符串數組
       
         for (int i = 0; i < RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
                sb.Append(  Random.Range(0, 3));//給字符串添加值
            }
            sb.AppendLine();  //換行
        }
         byte[] map = Encoding .UTF8.GetBytes(sb.ToString());//想獲得什麼類型的數據就Get什麼
        fs.Write(map, 0, map.Length);  //將Map寫到文件中,從map的第0個空間開始,長度爲length
        fs.Close();  //關閉流
        fs.Dispose();  //釋放資源
         AssetDatabase.Refresh();//刷新資源顯示
 
    }
 
}

 

A*算法

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections.Generic;
using  System.IO;
using  System.Text;
 
public  class AStar : MonoBehaviour {
 
     #region 字段
     byte[,] mapData; //存儲地圖數據的數組
     int rowCount; //地圖行數
     int colCount; //地圖列數
   
     string mappath;
     Transform Player; //小球
 
     Vector2 start; //起始點
     Vector2 end; //終止點
     Vector3 MoveDir; //移動的方向
     Vector3 Target; //移動的下一個目標
 
     //存放待訪問節點
     List< Node> list = new List< Node> ();
     //存放已經訪問過的節點
     List< Node> visited = new List< Node>();
     //存放小球的路徑點
     Stack< Vector2> path = new Stack< Vector2>();
 
     //方向
     Vector2[] dirs = new Vector2 [] { Vector2.left, Vector2.right, Vector2 .up, Vector2.down ,
     new Vector2(1, 1), new Vector2 (1, -1), new Vector2(-1, -1), new Vector2 (-1, 1) };
     #endregion
 
     #region 方法
     void Start()
    {
         string datapath = Application .dataPath + "/Map/Map2.txt";
        LoadMapData(datapath);  //加載地圖數據
        CreateMap();  //根據地圖數據建立地圖
        BFS();  //查找一條最優路徑
        Player =  GameObject.CreatePrimitive(PrimitiveType .Sphere).transform;
        Player.transform.position = GetPosition(start);
        Target = GetPosition(path.Peek());  //取出最上面的值
    }
 
     void Update()
    {
        MoveDir = (Target - Player.position).normalized;      
        Player.Translate(MoveDir *  Time.deltaTime);
         if (Vector3 .Distance(Player.position,Target)<0.1f)
        {
            path.Pop();  //出棧操做(取出來棧裏面就沒有該元素了)若是用Peek還會存在
 
             if (path.Count == 0)
            {
                 this.enabled = false ;//腳本失效
            }
             else
            {
                Target = GetPosition(path.Peek());
            }          
        }
    }
 
     void LoadMapData( string Path)
    {
   
         StreamReader sr = new StreamReader(Path);
         string content = sr.ReadToEnd();
         string[] Mapdata = content.Split(new string[] {"\r\n"},System.StringSplitOptions .RemoveEmptyEntries);//清除空格
        rowCount = Mapdata.Length;
        colCount = Mapdata[0].Trim().Length;
        mapData =  new byte [rowCount, colCount];
 
        //Debug.Log(rowCount +" "+ colCount);
         for (int i = 0; i < rowCount; i++)
        {
             for (int j = 0; j < colCount; j++)
            {
                mapData[i,j] =  byte.Parse(Mapdata[i][j].ToString());
                // Debug.Log(mapData[i,j]);
            }
        }      
        sr.Close();
        sr.Dispose();
    }
 
     Vector3 GetPosition( int x,int y)
    {     
         float pos_x = -rowCount * 0.5f + y;
         float pos_y = -colCount * 0.5f - x;
         return new Vector3(pos_x, 0, pos_y);
    }
     Vector3 GetPosition( Vector2 point)
    {
         float pos_x = -rowCount * 0.5f + point.y;
         float pos_y = -colCount * 0.5f - point.x;
         return new Vector3(pos_x, 1, pos_y);
    }
 
     /// <summary>
     /// 獲取起始點和終止點
     /// </summary>
     void GetStartEnd()
    {
         for (int i = 0; i < mapData.GetLength(0); i++)
        {
             for (int j = 0; j < mapData.GetLength(1); j++)
            {
                 if (mapData[i,j]==0)
                {
                    start.x = i;
                    start.y = j;
                }
                 else if (mapData[i,j]==9)
                {
                    end.x = i;
                    end.y = j;
                }
            }
        }
    }
     int NodeSort( Node x, Node y)
    {
         if (x.F == y.F)
        {
             return 0;//表示不交換位置
        }
         else if (x.F > y.F)
        {
             return 1;//表示交換位置
        }
         else
        {
             return -1;//表示不交換位置
        }
    }
 
     bool IsOk( Vector2 point)
 
   {
         //越界
         if (point.x<0||point.y<0||point.x>=mapData.GetLength(0)||point.y>= mapData.GetLength(1))
        {
             return false ;
        }
         //障礙物
         if (mapData[(int )point.x, (int)point.y]==2)
        {
             return false ;
        }
         //已訪問
         for (int i = 0; i < visited.Count; i++)
        {
             if (visited[i].x==(int )point.x&&visited[i].y==(int)point.y)
            {
                 return false ;
            }
        }
         for (int i = 0; i < list.Count; i++)
        {
             if (list[i].x == (int )point.x && list[i].y==(int)point.y)
            {
 
                 return false ;
            }
        }
         return true ;
    }
     //搜索最短路徑
     void BFS()
    {
         //給起始點和終止點賦值
        GetStartEnd();
         //建立起始節點看,進入隊列
         Node root = new Node(start);
        list.Add(root);
         //開始檢索
         while (list.Count > 0)
        {
             //先按照F值排序,後去F值最小的節點
            list.Sort(NodeSort);         
             Node node =list[0];
            list.Remove(node);  //移除,以跳出循環
            visited.Add(node);  //添加節點到已經訪問過的集合
             for (int i = 0; i < dirs.Length; i++)
            {
                 Vector2 point;
                point.x = node.x + dirs[i].x;
                point.y = node.y + dirs[i].y;
                 //判斷是否合法(是否越界 是不是障礙物)
                 if (IsOk(point))
                {
                     Node n = new Node(point,node);
                     if (i > 3)
                    {
                        n.G = node.G + 14;
                    }
                     else
                    {
                        n.G = node.G + 10;
                    }                  
                    n.CalculateH(end);
                    n.CalculateF();
                    list.Add(n);
                     if (point==end)
                    {
                         Debug.Log("Find!" );
                         Node p = n;//取出目標點
                         while (p != null )
                        {
                             //原路返回 將路徑點放到List數組中
                            path.Push(  new Vector2 (p.x, p.y));
                            p = p.Parent;                                
                        }
                         return;
                    }
                }
            }           
        }
    }
 
 
 
     void CreateMap()
    {
         GameObject Black = Resources .Load("Black") as GameObject ;
         GameObject Red = Resources .Load("Red") as GameObject ;
         GameObject Blue = Resources .Load("Blue") as GameObject ;
 
         for (int i = 0; i < mapData.GetLength(0); i++)
        {
             for (int j = 0; j < mapData.GetLength(1); j++)
            {
                 GameObject cube = null ;
                 switch (mapData[i, j])
                {
                     case 1:
                        cube =  GameObject.CreatePrimitive(PrimitiveType .Cube);                      
                         break;
                     case 2:
                        cube =  GameObject.Instantiate(Black);                       
                         break;
                     case 9:
                        cube =  GameObject.Instantiate(Blue);                      
                         break;
                     case 0:
                        cube =  GameObject.Instantiate(Red);                      
                         break;                      
                     default:
                         break;                       
                }
                cube.transform.SetParent(transform);
                 cube.transform.position = GetPosition(i, j);
                 //cube.transform.position = new Vector3(i, 0, j);
                cube.transform.localScale =  Vector3.one* 0.95f;
            }
        }
    }
     #endregion
 
 
}
 
 
 
 
另外一個腳本:Node類
 
using  UnityEngine;
using  System.Collections;
 
///  <summary>
///  節點模型類
///  </summary>
public  class Node  {
     //座標
     public int x, y;
     //記錄消耗值
     public int F, G, H;
     //父節點
     public Node Parent;
 
 
     //自動估算出H值,估計值
     public void CalculateH(Vector2 end)
    {
         this.H = (int )(10 * (Mathf.Abs(end.x - x) + Mathf.Abs(end.y - y)));
    }
     //自動估算F值
     public void CalculateF()
    {
         this.F = G + H;
 
    }
 
     public Node( int x,int y,Node parent= null)
    {
         this.x = x;
         this.y = y;
         this.Parent = parent;
    }
     public Node( Vector2 point, Node parent = null)
    {
         this.x = (int )point.x;
         this.y =(int )point.y;
         this.Parent = parent;
    }
 
 
}
 
 
 

 

二叉樹

做者: 1056923207@qq.com
  class  Node
    {
         public object Data;
         public Node Left;
         public Node Right;
    }
 
   class Program
    {
         static void Main(string[] args)
        {          
             Node node = BuildTree(7);
            TraverseTree(node);
 
        }
         /// <summary>
         /// 遞歸先序遍歷二叉樹
         /// </summary>
         public static void TraverseTree( Node node)
        {
             if (node==null )
            {
                 return;
            }
             Console.WriteLine(node.Data);
            TraverseTree(node.Left);
            TraverseTree(node.Right);
 
        }
         public static Node BuildTree( int rank)
        {
             Node root = new Node();
            root.Data = 1;
             Queue<Node > queue = new Queue< Node>();
            queue.Enqueue(root);
             int count = 1;
             while (count<rank)
            {
                count++;
 
                 Node child = new Node();
                child.Data = count;
                queue.Enqueue(child);
 
                 Node point = queue.Peek();
                 if (point.Left == null )
                {
                    point.Left = child;
                }
                 else
                {
                    point.Right = child;
                    queue.Dequeue();  //出隊列
                }
            }
             return root;
        }
 

 

遍歷二叉樹遞歸非遞歸

來源網址: http://blog.csdn.net/a497785609/article/details/4593224
做者: 1056923207@qq.com
遞歸實現先序中序後序遍歷二叉樹:
 
 
  •  //先序遍歷  
  •         static void PreOrder<T>(nodes<T> rootNode)  
  •         {  
  •             if(rootNode !=null )  
  •             {  
  •                 Console.WriteLine(rootNode.Data);  
  •                 PreOrder <T>(rootNode.LNode );  
  •                 PreOrder <T>(rootNode.RNode);  
  •             }  
  •         }  
  •         //中序遍歷二叉樹    
  •         static void MidOrder<T>(nodes<T> rootNode)   
  •         {    
  •             if (rootNode != null)    
  •             {    
  •                 MidOrder<T>(rootNode.LNode);    
  •                 Console.WriteLine(rootNode.Data);    
  •                 MidOrder<T>(rootNode.RNode);    
  •             }  
  •         }  
  •           
  •         //後序遍歷二叉樹   
  •         static void AfterOrder<T>(nodes<T> rootNode)    
  •         {    
  •             if (rootNode != null)    
  •             {    
  •                 AfterOrder<T>(rootNode.LNode);    
  •                 AfterOrder<T>(rootNode.RNode);   
  •                 Console.WriteLine(rootNode.Data);    
  •             }    
  •         }  

 

時間複雜度和空間複雜度

做者: 1056923207@qq.com
快速排序用來處理大量數據;
時間複雜度用o表示
一層循環:O(n);
二層循環:O(n2);冒泡排序
快排時間複雜度:O(n*Logn)
 
 

 

寬度優選尋路算法(BFS)

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections.Generic;
using  System.Text;
using  System.IO;
 
public  class Map : MonoBehaviour
{
 
     byte[,] data = new byte [5,5];
 
     void Start()
    {
        LoadMapData();
        BFSTest();
    }
 
     Queue< Vector2> queue = new Queue< Vector2>();
     //存放已經訪過的點
     List< Vector2> visited = new List< Vector2>();
     Vector2[] dirs = new Vector2 [] { Vector2.up, Vector2.right, Vector2 .down, Vector2.left };
 
     void BFSTest()
    {
         //起始點
         Vector2 start = Vector2 .zero;
         //起始點進入未訪問隊列
        queue.Enqueue(start);
         //終止點
         Vector2 end = Vector2 .one * 4;
         //只要有點能夠訪問,就繼續
         while (queue.Count>0)
        {
             //訪問一個點
             Vector2 currentPoint = queue.Dequeue();
             //標記該點已經訪問過
            visited.Add(currentPoint);
             //訪問先後左右
             for (int i = 0; i < dirs.Length; i++)
            {
                 Vector2 point;
                point.x = currentPoint.x + dirs[i].x;
                point.y = currentPoint.y + dirs[i].y;
                 if (IsOk(point))
                {
                    queue.Enqueue(point);
                     if (point.x==end.x&&point.y==end.y)
                    {
                         Debug.Log("Find!" );
                         return;
                    }
                }
            }
        }
         Debug.Log("Can't Find!" );
    }
     //標記是否已經訪問過
     bool IsOk( Vector2 point)
    {
         if (point.x<0||point.y<0||point.x>4||point.y>4)
        {
             return false ;
        }
         if (data[(int )point.x,(int)point.y]==2) //=2表明是障礙物,不能訪問 返回false
        {
             return false ;
        }
         //已經訪問過
         foreach (Vector2 item in visited)
        {
             if (item.x==point.x&&item.y==point.y)//已經訪問過的元素存入visited文件中
            {
                 return false ;
            }
        }
         return true ;
    }
 
     void LoadMapData()
    {
         string path = Application .dataPath + "/Map/Map1.txt";
         //文件讀寫流
         StreamReader sr = new StreamReader(path); //用來讀寫文件
         //讀取內容
         string result = sr.ReadToEnd();
         //逐行截取
         string[] data = result.Split(new char[] { '\n' });
         for (int i = 0; i < 5; i++)
        {
             for (int j = 0; j < 5; j++)
            {
                 this.data[i, j] = byte .Parse(data[i][j].ToString());
            }
        }
 
    }
 
}

 

編輯器擴展

做者: 1056923207@qq.com
[MenuItem("GameObject/Transform/Position")]
Static void Created()
{
 
 
}
 
點擊Position會觸發
 
 
 
實例:
 
using  UnityEngine;
using  System.Collections;
using  UnityEditor;
using  System.IO;
using  System.Text;
 
 
public  class MapBuilder : Editor{
 
 
 
     public const int RowCount = 20;
     public const int ColCount = 20;
 
 
    [ MenuItem (  "Map/Build")]
     static void BuildMap()
    {      
         //建立地圖10*10
         //規則:藍色是海洋,紅色是障礙物,黃色是終止點
         byte[,] map = GetMapData();
         GameObject Roads = new GameObject( "Roads");
         GameObject BlueCube = Resources .Load("Blue") as GameObject ;
         GameObject RedCude = Resources .Load("Red") as GameObject ;
         for (int i = 0; i <RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
              
                 switch (map[i,j])
                {
                     case 1:
                       GameObject RCube= Instantiate(RedCude) as GameObject;
                        RCube.transform.SetParent(Roads.transform);
                        RCube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f );
                        RCube.transform.localScale =  Vector3.one * 0.8f;
                        RCube.name = i.ToString() +  "_" + j.ToString();
                         break;
                     case 2:
                        GameObject Bcube= Instantiate(BlueCube) as GameObject;
                        Bcube.transform.SetParent(Roads.transform);
                        Bcube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f );
                        Bcube.transform.localScale =  Vector3.one * 0.8f;
                        Bcube.name = i.ToString() +  "_" + j.ToString();                
                         break;
                     default:
                       GameObject cube=  GameObject .CreatePrimitive(PrimitiveType.Cube);
                        cube.transform.SetParent(Roads.transform);
                        cube.transform.position =  new Vector3 (-17.5f + i, 0, j + 17.5f);
                        cube.transform.localScale =  Vector3.one * 0.8f;
                        cube.name = i.ToString() +  "_" + j.ToString();
                         break;
                }
            }
        }
    }
 
    [ MenuItem (  "Map/Test")]
     static byte[,] GetMapData()
    {
         string path = Application .dataPath + "/Map/Map1.txt";
         //文件讀寫流
         StreamReader sr = new StreamReader(path); //讀取文件而且將文件中的內容放到sr中      
         string result = sr.ReadToEnd(); //讀取內容(從當前位置到末尾讀取)       
         string[] data = result.Split(new char[] { '\n'});//逐行截取,生成的數據就是一行一行的
         byte[,] mapdata = new byte[RowCount, ColCount]; //定義一個二維數組
         Debug.Log(data.Length);
         for (int i = 0; i < RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
                mapdata[i, j] =  byte.Parse(data[i][j].ToString());//將字符串存入到二維數組
            }
        }
         return mapdata;
    }
 
 
    [ MenuItem (  "Map/CreateMap")]
     static void CreateMap()
    {
         //第一步訪問txt文件
         string path = Application .dataPath + "/Map/Map1.txt";
         FileStream fs= File .OpenWrite(path);//能夠對文件進行操做
         //第二步填充內容
         StringBuilder sb = new StringBuilder(); //容量可變的字符串數組
       
         for (int i = 0; i < RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
                sb.Append(  Random.Range(0, 3));//給字符串添加值
            }
            sb.AppendLine();  //換行
        }
         byte[] map = Encoding .UTF8.GetBytes(sb.ToString());//想獲得什麼類型的數據就Get什麼
        fs.Write(map, 0, map.Length);  //將字符寫到map中,從map的第0個空間開始,長度爲length
        fs.Close();  //關閉流
        fs.Dispose();  //釋放資源
 
    }
 
}

 

FileStream類

來源網址: http://www.jb51.net/article/45696.htm
做者: 1056923207@qq.com

對流進行操做時要引用 using System.IO; 命名空間

FileStream經常使用的屬性和方法:

屬性:

CanRead 判斷當前流是否支持讀取,返回bool值,True表示能夠讀取

CanWrite 判斷當前流是否支持寫入,返回bool值,True表示能夠寫入

方法:

Read() 從流中讀取數據,返回字節數組

Write() 將字節塊(字節數組)寫入該流

Seek() 設置文件讀取或寫入的起始位置

Flush() 清除該流緩衝區,使得全部緩衝的數據都被寫入到文件中

Close() 關閉當前流並釋放與之相關聯的全部系統資源

文件的訪問方式:(FileAccess)

包括三個枚舉:

FileAccess.Read(對文件讀訪問)

FileAccess.Write(對文件進行寫操做)

FileAccess.ReadWrite(對文件讀或寫操做)

文件打開模式:(FileMode)包括6個枚舉

FileMode.Append 打開現有文件準備向文件追加數據,只能同FileAccess.Write一塊兒使用

FileMode.Create 指示操做系統應建立新文件,若是文件已經存在,它將被覆蓋

FileMode.CreateNew 指示操做系統應建立新文件,若是文件已經存在,將引起異常

FileMode.Open 指示操做系統應打開現有文件,打開的能力取決於FileAccess所指定的值

FileMode.OpenOrCreate 指示操做系統應打開文件,若是文件不存在則建立新文件

FileMode.Truncate 指示操做系統應打開現有文件,而且清空文件內容

文件共享方式:(FileShare)

FileShare方式是爲了不幾個程序同時訪問同一個文件會形成異常的狀況。

文件共享方式包括四個:

FileShare.None 謝絕共享當前文件

FileShare.Read 充許別的程序讀取當前文件

FileShare.Write 充許別的程序寫當前文件

FileShare.ReadWrite 充許別的程序讀寫當前文件

使用FileStream類建立文件流對象:

FileStream(String 文件路徑,FileMode 文件打開模式)

FileStream(String 文件路徑,FileMode 文件打開模式,FileAccess 文件訪問方式)

FileStream(String 文件路徑,FileMode 文件打開模式,FileAccess 文件訪問方式,FileShare 文件共享方式)

例:

//在C盤建立a.txt文件,使用fs流對象對文件進行操做,fs的工做模式是新建(FileMode.Create)

FileStream fs=new FileStream(@"c:\a.txt",FileMode.Create);

//在C盤建立a.txt文件,使用fs流對象對文件進行操做,fs工做模式是新建(FileMode.Create)文件的訪問模式是寫入(Fileaccess.Write)

FileStream fs=new FileStream(@"c:\a.txt",FileMode.Create,FileAccess.Write);

//在C盤建立a.txt文件,使用fs流對象對文件進行操做,fs工做模式是新建(FileMode.Create)文件的訪問模式是寫入(FileAccess.Write)文件的共享模式是謝絕共享(FileShare.None)

FileStream fs=new FileStream(@"c:\a.txt",FileMode.Create,FileAccess.Write,FileShare.None);

使用File類來建立對象:(經常使用)

自定義打開文件的方式:File.Open(String,FileMode);

打開文件進行讀取: File.OpenRead(String);

打開文件進行寫入: File.OpenWrite(String);

示例以下:

//在C盤新建123.txt文件,使用流對象fs對文件進行操做,fs能夠行文件內容追加操做FileMode.Append

FileStream fs=File.Open(@"c:\123.txt",FileMode.Append);

//在C盤新建123.txt文件,使用流對象fs對文件進行操做,fs能夠進行讀文件File.OpenRead()

FileStream fs=File.OpenRead(@"c:\123.txt");

//在C盤新建123.txt文件,使用流對象fs對文件進行操做,fs能夠進行寫操做File.OpenWrite()

FileStream fs=File.OpenWrite(@"c:\123.txt");

使用File例:

對文件進行讀操做:

//新建fs流對象對象產生的路徑是textbox1.text的值,文件的模式是FileMode.OpenOrCreate(可讀可寫)

using (FileStream fs = File.Open(textBox1.Text, FileMode.OpenOrCreate))
{

//新建字節型數組,數組的長度是fs文件對象的長度(後面用於存放文件)
byte[] bt=new byte[fs.Length];

//經過fs對象的Read方法bt獲得了fs對象流中的內容
fs.Read(bt,0,bt.Length);

//關閉fs流對象
fs.Close();

//將bt字節型數組中的數據由Encoding.Default.GetString(bt)方法取出,交給textbox2.text
textBox2.Text = System.Text.Encoding.Default.GetString(bt);
}

對文件進行寫入操做:

//新建fs流對象,對象操做的文件路徑在textbox1.text中,fs的操做模式是FileMode.Create

using (FileStream fs = File.Open(textBox1.Text, FileMode.Create))
{

//新建字節型數組bt對象,bt對象獲得了textbox2.text的Encoding的值
byte[] bt = System.Text.Encoding.Default.GetBytes(textBox2.Text);

//將bt字節型數組對象的值寫入到fs流對象中(文件)
fs.Write(bt,0,bt.Length);

//關閉流對象
fs.Close();
}

注:

對文件的讀寫操多無論代碼有多少,無非就是下面的三步:

1.建立文件讀寫流對象

2.對文件進行讀寫

 
3.關閉文件流

 

攝像頭相關知識

來源網址: http://forum.china.unity3d.com/thread-622-1-1.html
做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
using  UnityEngine.UI;
 
public  class ExternalCamera : MonoBehaviour
{
     public static ExternalCamera _instance;
 
     public WebCamTexture cameraTexture;//攝像頭照到的圖片
 
     private Image img;
 
     void Awake()
    {
        _instance =  this;
 
        img = GetComponentInChildren<  Image>();//獲取子物體的組件
    }
 
     void Start()
    {
        StartCoroutine(CallCamera());  //開啓攜程
       
    }
 
     IEnumerator CallCamera()
    {
 
         yield return Application.RequestUserAuthorization( UserAuthorization.WebCam);//獲取yoghurt攝像頭權限
 
         if (Application .HasUserAuthorization(UserAuthorization.WebCam)) //若是擁有攝像頭權限
        {
             if (cameraTexture != null )//紋理存在
                cameraTexture.Stop();  //
             WebCamDevice[] device = WebCamTexture .devices;//將手機的兩個攝像頭存到數組
 
 
             //找出後置攝像頭 而且記錄下它的名字
             int index = 0;
             for (int i = 0; i < device.Length; i++)
            {
                 if (!device[i].isFrontFacing)//若是是後置攝像頭
                {
                    index = i;
                     break;
                }
            }
 
             string deviceName = device[index].name;//獲取後置攝像頭的名字
 
            cameraTexture =  new WebCamTexture (deviceName);//紋理使用後置攝像頭的額紋理
 
            img.canvasRenderer.SetTexture(cameraTexture);  //圖片的紋理
 
            cameraTexture.Play();  //啓用該紋理
        }
    }
}
 
 
 
 
 

WebCamTexture(攝像機開發須要用到的類)

[複製連接]
   

114

主題

504

帖子

5545

貢獻

版主

Rank: 7Rank: 7Rank: 7

積分
5545

灌水之王

QQ
電梯直達  跳轉到指定樓層
樓主
 發表於 2014-9-26 07:08:49 | 只看該做者 回帖獎勵
WebCamTexture類

命名空間: UnityEngine
繼承於: Texture

Description 說明
WebCam Textures are textures onto which the live video input is rendered.
攝像頭紋理是紋理到其上的實時視頻輸入呈現。

Static Variables
靜態變量
devices     返回可用的設備列表。

Variables
變量
deviceName          將其設置爲指定要使用的設備的名稱。
didUpdateThisFrame   檢查是否爲視頻緩衝後的最後一幀變化
isPlaying            判斷相機是否在播放
isReadable             判斷WebCamTexture是否可讀。 (僅適用於iOS的)
requestedFPS        設置相機裝置的請求的幀速率(每秒的幀數)
requestedHeight      設置相機裝置的要求高度
requestedWidth         設置相機裝置的要求寬度
videoRotationAngle       返回一個順時針方向的角度,它可用於旋轉的多邊形,以便相機內容顯示在正確的方位
videoVerticallyMirrored  紋理圖像是否垂直翻轉

Constructors
構造函數
WebCamTexture  建立WebCamTexture

Functions
功能
GetPixel     獲取位於座標(x,y)的像素顏色
GetPixels         獲得的像素顏色塊
GetPixels32     獲取原始格式的像素數據
MarkNonReadable 使WebCamTexture爲不可讀(無GetPixel*功能將可用(僅IOS))。
Pause      暫停相機功能
play             啓用
stop            中止

Inherited members
繼承的成員

Variables
變量

hideFlags     若是對象被隱藏,保存在場景或修改用戶
name         對象的名稱。
anisoLevel     紋理的各向異性過濾級別
filterMode     紋理過濾模式
height         像素紋理的高度(只讀)
mipMapBias     MIP映射紋理偏見
width          像素紋理的寬度 (只讀)
wrapMode     換行模式的紋理(重複或鉗.

Functions
功能

GetInstanceID         返回該對象的實例ID
ToString         返回遊戲對象的名稱
GetNativeTextureID     檢索本地('硬件')處理到紋理
GetNativeTexturePtr     檢索本機('硬件')處理到紋理.

Static Functions
靜態函數
Destroy         刪除一個遊戲物體,組件
DestroyImmediate     當即銷燬對象
DontDestroyOnLoad     在加載裝載一個新的場景時,使該對象的目標不會被自動銷燬FindObjectOfType     返回第一個加載的對象的類型。
FindObjectsOfType     返回全部加載對象的類型列表。
Instantiate         實例化一個對象
SetGlobalAnisotropicFilteringLimits     設置各向異性的限制

Operators
操做運算符
bool         真假
operator !=     不等於
operator ==     等於

 

掃雷遊戲

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
using  UnityEngine.EventSystems;
using  UnityEngine.UI;
///  <summary>
///  格子類
///  </summary>
public  class Grid
{
     public bool IsLei;//是不是雷
     public bool IsClicked;//是否點擊了
     public byte Count;//周圍有幾個雷
}
 
public  class Map : MonoBehaviour, IPointerClickHandler//繼承點擊事件的接口函數
{
 
     #region 常量
     public const int RowCount = 10;//行數
     public const int ColCount = 10;//列數
     #endregion
 
     #region 字段
     private Grid[,] grids = new Grid[RowCount, ColCount]; //存儲格子的數組
     private GameObject[,] tiles = new GameObject[RowCount, ColCount]; //存儲預設體實例化對象的的數組
     private Vector2[] dirs = new Vector2[] { Vector2.up, Vector2 .down, Vector2.left, Vector2.right, new Vector2(-1, 1), new Vector2(-1, -1), new Vector2 (1, 1), new Vector2(1, -1) }; //格子周圍八個方塊
    [ SerializeField ]
     private Transform gridContainer;
    [ SerializeField ]
     private GameObject gridPrefab;
     #endregion
 
     #region 方法
     //初始化遊戲
     public void StartGame()
    {
         for (int i = 0; i < RowCount; i++)
        {
             for (int j = 0; j < ColCount; j++)
            {
                 //注意兩個數組的座標是一致的
                 //下面兩句主要是給格子初始化,那些有雷,那些沒有雷
                grids[i, j] =  new Grid ();//初始化格子
                grids[i, j].IsLei =  Random.Range(1, 11) > 2 ? false : true;//是不是雷
 
                 GameObject grid = (GameObject )Instantiate(gridPrefab);//建立格子
                grid.transform.SetParent(gridContainer);  //放到格子中
                grid.name = i.ToString() +  "_" + j.ToString();//格子的名字就是xy座標中間加"_";便於後面運算
                tiles[i, j] = grid;  //將實例化出來的button放到數組中
            }
        }
    }
     /// <summary>
     /// 格子點擊
     /// </summary>
     /// <param name="x"> The x coordinate.</param>
     /// <param name="y"> The y coordinate.</param>
     public void GridClick(int x, int y)
    {
         if (!grids[x, y].IsClicked)
        {  //若是格子沒有點擊過
            grids[x, y].IsClicked =  true;
             if (grids[x, y].IsLei)
            {
                print(  "輸了");
                 return;
            }
             for (int i = 0; i < dirs.Length; i++)
            {
                 int temp_x = x + (int )dirs[i].x;
                 int temp_y = y + (int )dirs[i].y;
                 //判斷是否越界
                 if (temp_x >= 0 && temp_x < RowCount && temp_y >=  0 && temp_y < ColCount)
                {
                     if (grids[temp_x, temp_y].IsLei)
                    {
                        grids[x, y].Count++;  //當前格子周圍的雷數+1
                    }
                }
            }
 
            tiles[x, y].transform.GetChild(0).gameObject.SetActive(  true);//把Text腳本激活用來顯示雷數
            tiles[x, y].GetComponent<  Image>().color = Color .gray;//改變顏色
             if (grids[x, y].Count > 0)
            {
                // Debug.Log("Click");
                tiles[x, y].GetComponentInChildren<  Text>().text = grids[x, y].Count.ToString();
            }
             else
            {
                DiGui(x, y);
            }
 
        }
 
    }
     /// <summary>
     /// 遞歸
     /// </summary>
     /// <param name="x"> The x coordinate.</param>
     /// <param name="y"> The y coordinate.</param>
     public void DiGui(int x, int y)
    {
         for (int i = 0; i < dirs.Length; i++)
        {
             int temp_x = x + (int )dirs[i].x;
             int temp_y = y + (int )dirs[i].y;
             //判斷是否越界
             if (temp_x > 0 && temp_x < RowCount && temp_y > 0 && temp_y < ColCount)
            {
                GridClick(temp_x, temp_y);
            }
        }
    }
     #endregion
 
     void Start()
    {
        StartGame();
    }
 
     //鼠標點擊格子觸發函數
     public void OnPointerClick(PointerEventData eventData)
    {
        // Debug.Log("LLL");
         GameObject enter = eventData.pointerEnter;
         //若是是格子
         Debug.Log(enter.name);
         if (enter.name.Contains("_" ))
        {
          
             int x = int .Parse(enter.name.Split('_')[0]);
             int y = int .Parse(enter.name.Split('_')[1]);
            GridClick(x, y);
             Debug.Log("LLL" );
 
        }
    }
 
 
}

 

遞歸

做者: 1056923207@qq.com
先調用和先打印書序反告終果也會反;

 

屏幕座標轉世界座標(好用)

來源網址: http://www.tuicool.com/articles/Rjiqeq
做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
 
public  class CubeTest : MonoBehaviour {   
         void Update () {
         Vector3 Screen_point = Input .mousePosition;
        Screen_point +=  new Vector3 (0, 0, transform.position.z - Camera.main.transform.position.z);
        transform.position =  Camera.main.ScreenToWorldPoint(Screen_point);
     
        // Debug.Log(transform.position);
                }
}
 
 
攝像機座標系:0到1
屏幕座標是:
 
 
 

unity3d 屏幕座標、鼠標位置、視口座標和繪製GUI時使用的座標

時間 2012-12-30 19:58:00  博客園-原創精華區
主題  Unity3D

unity3d中的屏幕座標系 是以 屏幕  左下角爲(0,0)點 右上角爲(Screen.Width,Screen.Height)

鼠標位置座標與屏幕座標系一致

視口座標是以攝像機爲準  以屏幕的左下角爲(0,0)點 右上角爲(1,1)點

繪製GUI界面時使用的座標是以  屏幕  的左上角爲(0,0)點 右下角爲(Screen.width,Screen,Height)

常常會用到 某個物體的世界座標到屏幕座標的轉化而後再屏幕上繪製出這個物體的表明性圖片

是這樣作的

一、Vector3 ScreenPos=Camera.WorldToScreenPoint(trans.Position);

二、GUIPos=new Vector3(ScreenPos.x,Screen.height-ScreenPos.y,0);

 
而後按照這個座標繪製圖片就能夠了

 

網絡相關知識

做者: 1056923207@qq.com
1:引入命名空間 Using system.Net和using System.Net.Sockets;
2:服務器代碼;
 
Socket mConn = new Socket(AddressFamily.InterNetWork, SocketType.Stream,  ProtocoType.Tcp);
int Port = 7777;
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any,  Port);
mConn.Bind(endpoint);
mConn.Listen(10);
a:同步接收客戶端的代碼(在當前客戶端沒有鏈接以前,不能進行其餘操做 只能等着)
while (true)
{
Socket client = mConn.Accept();
Console.WriteLine("有客戶端鏈接");
}
b:異步接收客戶端代碼
 
mConn.BeginAccept(AcceptClient,mConn)
Console.ReadLine();//(這個方法也是至關於同步方法)保持服務器一直開着,
 
private static void AcceptClient(IAsyncResult ar)
{
Console.WriteLine("有客戶端鏈接");
Socket server= ar。AsyncState as Socket;
Socket client = server.EndAccept(ar);
Console.WriteLine(client.RemoteEndPoint);//打印鏈接的客戶端的IP地址
//再次開啓異步接收
server.BeginAccept(AcceptCllient,server);
}
 
 
 
 
客戶端代碼:
 
using  UnityEngine;
using  System.Collections;
using  UnityEngine.Networking;
using  System.Net;
using  System.Net.Sockets;
public  static class MyNetWork
{
 
 
     private static Socket mConn;
     /// <summary>
     /// 開啓服務器
     /// </summary>
    // public static void StartServer(int port = 7777)
    // {
          // mConn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Tcp可靠,Udp不可靠
                                                                                             //Http Https  Http不加密 傳輸速度快 不安全 HTTPS加密
        // IPEndPoint endpoinnt = new IPEndPoint(IPAddress.Any, port);
 
       //  mConn.Bind(endpoinnt);//看似器服務器以前必須綁定IP和端口
       //  mConn.Listen(11);
 
 
   //  }
     /// <summary>
     /// 開啓客戶端
     /// </summary>
     /// <param name="endPoint"></param>
     public static void StartClient(IPEndPoint endPoint)
    {
        mConn =  new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType .Tcp);
        mConn.Connect(endPoint);
         Debug.Log(mConn.Connected);
    }
 
 
}
 
 
3:客戶端調用方法
 
 
using  UnityEngine;
using  System.Collections;
using  System.Net.Sockets;
using  System.Net;
 
public  class Testtt : MonoBehaviour {
 
 
        void Start () {
         //  MyNetWork.StartServer();
         //IPAddress ipaddress = IPAddress.Parse("172.18.21.139");
        IPAddress ipaddress = IPAddress .Parse("127.0.0.1");
         int port = 7777;
         IPEndPoint endpoint = new IPEndPoint(ipaddress,port);
         MyNetWork.StartClient(endpoint);
         Debug.Log("連接服務器成功" );
                }                 
}
 
 

 

異步加載場景

做者: 1056923207@qq.com
1:第一個場景Button上掛載的腳本 要加載滴二哥場景
using  UnityEngine;
using  System.Collections;
using  UnityEngine.UI;
 
public  class Test : MonoBehaviour {
 
 
     void Start()
    {
        GetComponent<  Button>().onClick.AddListener(LoadScene);
    }
 
   
     public void LoadScene()
    {
         LoadingManager.Instance.LoadScene("2" );     
    }
}
 
2:單例類加載管理器
using  UnityEngine;
using  System.Collections;
using  UnityEngine.SceneManagement;
 
public  class LoadingManager {
 
     #region 屬性
     public static LoadingManager instace;
      private AsyncOperation mAsync;
 
     private string scenename;
 
         public  string Name
    {
         get
        {
             return scenename;
        }
 
 
    }
     public static LoadingManager Instance
    {
         get {
 
             if (instace==null )
            {
                instace =  new LoadingManager ();
            }
             return instace;
        }
   }   
     #endregion
 
 
     #region 方法
     public void LoadScene(string SceneName)
    {
         SceneManager.LoadScene("Login" );
         //(同步方法)場景名字加載場景
           //mAsync = SceneManager.LoadSceneAsync(SceneName);
         // mAsync.allowSceneActivation =false;
 
         this.scenename = SceneName;
    }
 
3:Login場景中的腳本
using  UnityEngine;
using  System.Collections;
using  UnityEngine.SceneManagement;
using  UnityEngine.UI;
public  class Loading : MonoBehaviour {
 
     private AsyncOperation mAsync=null ;//異步加載場景的返回值
     private string targetScene;
     private int mProgress = 0;//表示當前進度
     private int mCurrent = 0;//表示實際進度
     private Slider mSlider;//進度條
 
     void Awake()
    {
 
        mSlider = GetComponent<  Slider>();
 
    }
                  void Start ()
    {
        targetScene =  LoadingManager.Instance.Name;      
        mAsync =  SceneManager.LoadSceneAsync(targetScene);
        mAsync.allowSceneActivation =  false;
         //print(LoadingManager.Instance.Name);
      
       
    }
 
 
     void Update()
    {
        mCurrent = System.  Convert.ToInt32(mAsync.progress * 100);
      
         if (mCurrent==90)
        {
            mProgress = 100;
        }
         if (mProgress == 100)//表示進度完成
        {          
            mAsync.allowSceneActivation =  true;           
        }
         else
        {
          
             if (mProgress<mCurrent)
            {
               
                mProgress++;
                mSlider.value = mProgress / 10000f;
            }
        }
        print(mAsync.progress);
                
                }
}
 
 
 
 
     #endregion
 
}

 

SDK/Json

做者: 1056923207@qq.com
1:分享功能:
 
第一個腳本:取到Json字符串;
 
using  UnityEngine;
using  System.Collections;
using  System.Net;
using  System.IO;
using  LitJson;
 
public  class HttpUtility
{
 
     /// <summary>
     /// Get請求,獲取內容
     /// </summary>
     /// <param name="url"> 網址</param>
     public static string GetHttpText(string url)
    {
         //建立一個Http請求對象
         HttpWebRequest request = HttpWebRequest .Create(url) as HttpWebRequest;
         //獲取相應對象
          WebResponse response =  request.GetResponse();
         //獲取相應的內容
         Stream steam = response.GetResponseStream();
 
         StreamReader sr = new StreamReader(steam);
 
 
         string result = sr.ReadToEnd();
 
        sr.Close();
        sr.Dispose();
         return result;
 
       
      
     
 
         //WWW www = new WWW(url);
         //while (!www.isDone)
         //{
 
         //}
         //string result = www.text;
         //return result;
    }
 
 
 
 
     //public static T GetHttpText<T>(string url) where T:class
     //{
     //    //建立一個Http請求對象
     //    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
     //    //獲取相應對象
     //    WebResponse response = request.GetResponse();
     //    //獲取相應的內容
     //    Stream steam = response.GetResponseStream();
 
     //    StreamReader sr = new StreamReader(steam);
 
 
     //    T result = sr.ReadToEnd() as T;
 
     //    sr.Close();
     //    sr.Dispose();
     //    return result;
 
       
 
 
 
     //    //WWW www = new WWW(url);
     //    //while (!www.isDone)
     //    //{
 
     //    //}
     //    //string result = www.text;
     //    //return result;
     //}
 
     //public static Weatherdata SetWeatherData(string jsonData)
     //{
     //    try
     //    {
     //        return JsonMapper.ToObject<Weatherdata>(jsonData);
     //    }
     //    catch (System.Exception ex)
     //    {
     //        UnityEngine.Debug.Log(ex.ToString());
     //        return null;
     //    }
 
     //}
 
}
 
 
第二個腳本:根據Json字符串的格式定義一個接收Json轉換成Object對象的數據結構
 
 
using  UnityEngine;
using  System.Collections;
 
 
 
    [System. Serializable ]
     public class Weather
    {
         public string retCode;          // 返回碼
         public string msg;              //  返回說明
         public WeatherData [] result;
    }
 
 
 
    [System. Serializable ]
     public class WeatherData
    {
     
         public string airCondition;     //  空氣質量
         public string city;             //  城市
         public string coldIndex;        //  感冒指數
         public string updateTime;       //  更新時間
         public string date;             //  日期
         public string distrct;          //  區縣
         public string dressingIndex;    //  穿衣指數
         public string exerciseIndex;    //  運動指數
         public Future [] future;
         public string humidity;         //  溼度
         public string pollutionIndex;   //  空氣質量指數
         public string province;         // 省份
         public string sunset;           // 日落時間
         public string sunrise;          // 日出時間
         public string temperature;      //  溫度
         public string time;             // 時間
         public string washIndex;        //  洗車指數
         public string weather;          //  天氣
         public string week;             // 星期
         public string wind;             // 風向
    }
    [System. Serializable ]
     public class Future
    {
         public string date;             //  日期
         public string dayTime;          //  白每天氣
         public string night;            //  晚上天氣
         public string temperature;      //  溫度
         public string week;             // 星期
         public string wind;             // 風向
    }
 
第三個腳本:測試腳本,將前兩個腳本連接起來
 
 
 
using  UnityEngine;
using  System.Collections;
using  LitJson;
 
public  class Testt : MonoBehaviour {
 
                  // Use this for initialization
                  void Start () {
         string result = HttpUtility .GetHttpText(Const.WeatherApiURL);
      
         JsonData nn = JsonMapper .ToObject(result);
         Weather kk = JsonMapper .ToObject<Weather>(result);
         Debug.Log(kk.result[0].wind);
        // Debug.Log(mm.result[0].future[0].date);
        // Debug.Log(nn[0]);
 
         //Debug.Log();
 
       
 
    }
                
                  // Update is called once per frame
                  void Update ()
    {
                
                }
}
 
 
 
 
 
  
 
 

 

馬帥的攝像機

做者: 1056923207@qq.com

 

DataBaseTool

做者: 1056923207@qq.com
/*******************
********************/
using  UnityEngine;
using  System.Collections;
using  System.Collections.Generic;
using  Mono.Data.Sqlite;
 
///  <summary>
///  數據庫操做的單例類
///  </summary>
public  class DataBaseTool
{
     private static DataBaseTool _instance;//單例的靜態引用
     public static DataBaseTool Instance
    {
         get
        {
             if (_instance == null )
            {
                _instance =  new DataBaseTool ();
            }
             return _instance;
        }
    }
 
     private string databaseName = "IslandDatabase.sqlite" ;//數據庫名稱
     //數據庫連接對象
     private SqliteConnection sqlConnection = null ;
     //數據結果
     private SqliteDataReader sqlDataReader = null ;
 
     /// <summary>
     /// 初始化數據庫相關對象
     /// </summary>
     private DataBaseTool()
    {
         //數據庫連接地址
         string path = "Data Source=" + Application.streamingAssetsPath + "/" + databaseName;
 
         if (sqlConnection == null )
        {
             try
            {
                sqlConnection =  new SqliteConnection (path);
            }
             catch (SqliteException e)
            {
                 Debug.Log("建立數據庫連接失敗..." );
                 Debug.Log(e.ToString());
            }
        }
    }
 
     /// <summary>
     /// 打開數據庫連接
     /// </summary>
     private void OpenConnection()
    {
         if (sqlConnection != null )
        {
             try
            {
                sqlConnection.Open();
            }
             catch (SqliteException e)
            {
                 Debug.Log("打開數據庫連接失敗..." );
                 Debug.Log(e.ToString());
            }
        }
         else {
             Debug.Log("打開數據庫連接失敗..." );
        }
    }
 
     /// <summary>
     /// 關閉數據庫連接
     /// </summary>
     private void CloseConnection()
    {
         if (sqlConnection != null )
        {
             try
            {
                sqlConnection.Close();
            }
             catch (SqliteException e)
            {
                 Debug.Log("關閉數據庫連接失敗..." );
                 Debug.Log(e.ToString());
            }
        }
         else {
             Debug.Log("關閉數據庫連接失敗..." );
        }
    }
 
     /// <summary>
     /// 執行增、刪、改數據庫操做
     /// </summary>
     public void ExcuteSql(string sqlStr)
    {
        OpenConnection();
         SqliteCommand sqlCommand = sqlConnection.CreateCommand();
         if (sqlCommand != null )
        {
            sqlCommand.CommandText = sqlStr;
             int result = sqlCommand.ExecuteNonQuery();
        }
         else {
             Debug.Log("執行數據庫命令失敗..." );
        }
 
        CloseConnection();
    }
 
     /// <summary>
     /// 得到一行數據的方法
     /// </summary>
     public Dictionary<string , object> ExcuteOneClumeResult( string sql)
    {
        OpenConnection();
         Dictionary<string , object> result = new Dictionary <string, object>();
         SqliteCommand sqlCommand = sqlConnection.CreateCommand();
         if (sqlCommand != null )
        {
            sqlCommand.CommandText = sql;
            sqlDataReader = sqlCommand.ExecuteReader();
             while (sqlDataReader.Read())
            {
                 for (int i = 0; i < sqlDataReader.FieldCount; i++)
                {
                    result.Add(sqlDataReader.GetName(i), sqlDataReader.GetValue(i));
                }
                 break;
            }
        }
         else {
            result =  null;
        }
        CloseConnection();
         return result;
    }
 
     /// <summary>
     /// 返回查詢的全部數據(多列)
     /// </summary>
     /// <returns>The all rresult.</returns>
     public List<Dictionary <string, object>> ExcuteAllRresult(string sql)
    {
        OpenConnection();
         //存放查詢的全部結果集
         List<Dictionary <string, object>> results
            =  new List <Dictionary< string, object >>();
         SqliteCommand sqlCommand = sqlConnection.CreateCommand();
         if (sqlCommand != null )
        {
             //打包sql語句
            sqlCommand.CommandText = sql;
             //執行sql語句並得到查詢結果
            sqlDataReader = sqlCommand.ExecuteReader();
             //逐行解析數據
             while (sqlDataReader.Read())
            {
                 //單行數據的全部內容
                 Dictionary<string , object> oneclum = new Dictionary <string, object>();
                 for (int i = 0; i < sqlDataReader.FieldCount; i++)
                {
                    oneclum.Add(sqlDataReader.GetName(i), sqlDataReader.GetValue(i));
                }
                results.Add(oneclum);
            }
        }
 
        CloseConnection();
         return results;
    }
}

 

泛型單例父類

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
 
public  abstract class MonoSingle< T> : MonoBehaviour where T :MonoBehaviour
{
     private static T instance;
     public static T Instance
    {
         get
        {
             return instance;
        }
    }
     public virtual void Awake()
    {
        instance =  this as T;
    }
}
 
這個單例父類的做用就是當有多個類須要寫成單例是,不用重複寫單例;
@其餘的類繼承這個類就能夠當作單例使用,例以下例:(注意繼承的方式)
 
 
using  UnityEngine;
using  System.Collections;
///  <summary>
///  聲音控制器,單例類
///  </summary>
public  class SoundController : MonoSingle<SoundController >
{
     AudioSource m_bgMusic;
     public override void Awake()
    {
         base.Awake();//繼承基類的方法
        m_bgMusic = gameObject.AddComponent<  AudioSource>();//獲取AudioSource組件
        m_bgMusic.loop =  true;//循環播放
        m_bgMusic.playOnAwake =  false;       
    }
     //播放背景音樂
     public void PlayBG(string bgName)
    {    
         string currentBgName = string .Empty;//定義一個空的string類型變量
         if (m_bgMusic !=null )//若是存在AudioSoruce組件
        {                       
                currentBgName = m_bgMusic.name;  //獲取組件的名字                    
        }
      
 
             if (bgName == currentBgName)
            {
                 return;//若是傳進來的生意與原來的聲音同樣 就不用從新開始播放啦
                 Debug.Log("------" );
            }
       
 
         AudioClip clip = Resources .Load<AudioClip>(bgName); //加載聲音資源
         if (clip!=null )//若是存在聲音資源
        {
            m_bgMusic.clip = clip;  //給聲音組件賦值
            m_bgMusic.Play();  //播放聲音組件
        }
 
 
    }
 
     /// <summary>
     /// 播放特效音樂
     /// </summary>
     /// <param name="Effectname"></param>
     public void PlayEffect(string Effectname,float volume = 1f)
    {
         AudioClip clip = Resources .Load<AudioClip>(Effectname); //加載聲音資源
         if (clip!=null )//若是聲音資源不爲空
 
        {              
             AudioSource.PlayClipAtPoint(clip, transform.position);
        }
    }
}

 

關於AudioSource和AudioClip的使用

做者: 1056923207@qq.com
1:實例一個AudioSource的對象:    AudioSource m_bgMusic;
2:實例化一個AudioClip的對象,而且賦一個值: AudioClip  clip = Resources .Load<AudioClip>(bgName);
3: m_bgMusic.clip = clip;  //給聲音組件賦值
4:    m_bgMusic.Play();  //播放聲音組件
 
 
 
 
using  UnityEngine;
using  System.Collections;
 
///  <summary>
///  聲音控制器,單例類
///  </summary>
public  class SoundController : MonoSingle<SoundController >
{
     AudioSource m_bgMusic;
     public override void Awake()
    {
         base.Awake();//繼承基類的方法
        m_bgMusic = gameObject.AddComponent<  AudioSource>();//獲取AudioSource組件
        m_bgMusic.loop =  true;//循環播放
        m_bgMusic.playOnAwake =  false;       
    }
     //播放背景音樂
     public void PlayBG(string bgName)
    {
      
         string currentBgName = string .Empty;//定義一個空的string類型變量
         if (m_bgMusic !=null )//若是存在AudioSoruce組件
        {                       
                currentBgName = m_bgMusic.name;  //獲取組件的名字                    
        }
      
 
             if (bgName == currentBgName)
            {
                 return;//若是傳進來的生意與原來的聲音同樣 就不用從新開始播放啦
                 Debug.Log("------" );
            }
       
 
         AudioClip clip = Resources .Load<AudioClip>(bgName); //加載聲音資源
         if (clip!=null )//若是存在聲音資源
        {
            m_bgMusic.clip = clip;  //給聲音組件賦值
            m_bgMusic.Play();  //播放聲音組件
        }
 
 
    }
 
     /// <summary>
     /// 播放特效音樂
     /// </summary>
     /// <param name="Effectname"></param>
     public void PlayEffect(string Effectname,float volume = 1f)
    {
         AudioClip clip = Resources .Load<AudioClip>(Effectname); //加載聲音資源
         if (clip!=null )//若是聲音資源不爲空
 
        {              
             AudioSource.PlayClipAtPoint(clip, transform.position);
        }
    }
}

 

類能夠繼承 結構體不能繼承;

做者: 1056923207@qq.com
類能夠繼承  結構體不能繼承;
接口和抽象類的區別:接口不能被實現,只能聲明

 

動畫插件Itween和dotween

做者: 1056923207@qq.com
 
本身定義的MyTween腳本:
 
using  UnityEngine;
using  System.Collections;
 
public  class MyTween : MonoBehaviour
{
 
     #region 字段
     public Vector3 position;
     public float time, delay;
     public LoopType looptype;
     public EaseType easetype;
 
 
     #endregion
 
 
 
     #region 枚舉
 
 
     public enum LoopType
    {
        Once,
        Loop,
        Pingppang
    }
 
     public enum EaseType
    {
        Liner,
        Spring
    }
 
 
     #endregion
 
     #region  註冊方法
 
     public static void MoveTo(GameObject go, Hashtable args)
    {
         MyTween tween = go.AddComponent<MyTween >();
         if (args.Contains("position" ))
        {
            tween.position =(  Vector3)args["position" ];
        }
 
         if (args.Contains("time" ))
        {
            tween.time = (  float)args["time" ];
 
        }
         if (args.Contains("delay" ))
        {
            tween.delay = (  float)args["delay" ];
 
        }
         if (args.ContainsKey("loopType" ))
        {
            tween.looptype = (  LoopType)System.Enum .Parse(typeof( LoopType), args["loopType" ].ToString());//字符串強轉成枚舉得方法
        }
 
    }
 
 
     #endregion
     #region 方法
     private float timer;
     void MoveTo()
    {
        timer +=  Time.deltaTime;//計時
         if (timer>delay)
        {
             //若是是平滑移動,保持起始點和終點不變 只有時間邊
             //若是是先快後慢,保證時間和終點不變,起始點變化
             //Lerp公式:from +(to -from)*time,time= [0,1]
            transform.position =  Vector3.Lerp(transform.position, position, (timer - delay)/time);
        }
         if (timer>delay+time)//一段時間後銷燬本腳本
        {
             if (looptype==LoopType .Once)//若是循環的類型爲單次
            {
                Destroy(  this);
            }
        }
 
    }
 
   
     #endregion
 
     void Update()
    {
        Invoke(  "MoveTo",0f);
    }
 
}
 
 
 
調用MyItween的Test腳本:
 
using  UnityEngine;
using  System.Collections;
 
public  class Test : MonoBehaviour {
 
     Hashtable har;
     // Use this for initialization
     void Start () {
         //是一個集合(哈希表),能夠存儲任意類型
     har =  new Hashtable();
        har.Add(  "amount", Vector3 .one*180);
        har.Add(  "position", Vector3 .one * 3);
        har.Add(  "time", 5f);
        // har.Add("Time", 3f);
        har.Add(  "delay", 1f);
        har.Add(  "loopType", MyTween .LoopType.Once);
        har.Add(  "easeType", MyTween .EaseType.Liner);
        har.Add(  "rotation", Vector3 .up * 180);
         // iTween.RotateTo(gameObject, har);
         //iTween.ShakePosition(gameObject, har);
         //iTween.ShakeRotation(gameObject,har);
         MyTween.MoveTo(gameObject, har);
   
                }
                
                  // Update is called once per frame
                  void Update () {
        // iTween.MoveUpdate(gameObject, har);
    }
}
 
 
 
 
 
調用的Test腳本
 
using  UnityEngine;
using  System.Collections;
 
public  class Test : MonoBehaviour {
 
     Hashtable har;
     // Use this for initialization
     void Start ()
    {
         //是一個集合(哈希表),能夠存儲任意類型
        har =  new Hashtable ();
        har.Add(  "amount", Vector3 .one*180);
        har.Add(  "position", Vector3 .one * 3);
        har.Add(  "time", 5f);
        // har.Add("Time", 3f);
        har.Add(  "delay", 1f);
        har.Add(  "loopType", MyTween .LoopType.Once);
        har.Add(  "easeType", MyTween .EaseType.Liner);
        har.Add(  "rotation", Vector3 .up * 180);
         // iTween.RotateTo(gameObject, har);
         //iTween.ShakePosition(gameObject, har);
         //iTween.ShakeRotation(gameObject,har);
         MyTween.MoveTo(gameObject, har);//靜態方法經過類名點調用;非靜態方法經過對象調用
     
      
      
       
                }
                
                  // Update is called once per frame
                  void Update () {
        // iTween.MoveUpdate(gameObject, har);
    }
}
 
 
 

 

關於技能的釋放

做者: 1056923207@qq.com
1;從數據庫英雄表取出數據  用逗號分割,存入string數組;
  this .skillsname = heroData[  "Skills"].ToString().Split(',' );
2:將這些string類型的轉成int類型,存入整形數組(容量大小與string類型的數組相同);
3:根據這些id在數據結構裏面初始化技能;mskills存儲的是技能數據結構,由於這個腳本是在aunit裏面  aunit在人物身上,因此有aunit腳本的就能夠調用技能數據。在UIController裏面添加對應英雄的aunit腳本就能夠調用技能數據;
this .skillsname = heroData[ "Skills"  ].ToString().Split(',');
                mSkillsId =  new int [skillsname.Length];
                 this.mSkills = new SkillData[skillsname.Length];
                 //初始化技能數據
                 for (int i = 0; i < skillsname.Length; i++)
                {
                    mSkillsId[i] =  int.Parse(skillsname[i]);
                     this.mSkills[i].InitSkillData(this .mSkillsId[i]);
                }
 

 

跨腳本調用方法

做者: 1056923207@qq.com
若是方法是靜態的 就經過類名(腳本名字)調用;
若是方不是靜態的:就經過實例化對象  而後點的方法調用(方法必須是公有的才能點出來)

 

改變鼠標指針單例腳本,在其餘腳本中能夠調用

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
using  UnityEngine.UI;
public  class NYBTest : MonoBehaviour
{
     public static NYBTest _instance;
 
 
     public Texture2D normal;
     public Texture2D npc;
     public Texture2D attack;
     public Texture2D locktarget;
     public Texture2D pick;
 
 
     private Vector2 hotspot = Vector2 .zero;
     private CursorMode mode = CursorMode .Auto;
 
     void Start()
    {
 
        _instance =  this;
    }
     public void SetNormal()
    {
 
         Cursor.SetCursor(normal, hotspot, mode);
    }
     public void NPC()
    {
 
         Cursor.SetCursor(npc, hotspot, mode);
    }
 
 
 
}

 

xml寫的Transform和Json

做者: 1056923207@qq.com
 
 
Json:
 
Json寫的transform:
 
 

 

委託

做者: 1056923207@qq.com
委託是講方法做爲參數進行傳遞方法既能夠是靜態方法,又能夠是實例方法
委託的聲明圓形以下:
delegate <函數返回類型><委託名>(<函數參數>)
 
委託主要用來實現回調:
 
委託是的使用步驟
 
 
 

 

屬性,數據類型,方法參數

做者: 574096324@qq.com
屬性
class Car
    {
         private string brand;
         public double price;
         //get,set也稱爲屬性
         public string GetBrand()
        {
             return brand;
        }
         public void SetBrand(string c)
        {
            brand = c;
        }
         public double GetPrice()
        {
             return price;
        }
         public void SetPrice(double p)
        {
            price = p;
        }
    }
 
屬性 簡寫
public  double Price
        {
             get;
             set;
        }
數據類型
數據在內存中的空間分配
*棧區:值類型定義的變量  壓棧,出棧
*堆區:數組,對象
常量區:常量
靜態區:Main前面static,字段用static修飾在 靜態區
代碼區:方法
 
方法參數

 

新版網絡

做者: 1056923207@qq.com
1;端口:每一個端口對應一個服務 
 
2:新版網絡的API:
 
 
 
 
Unity 網絡服務器:NetWorkServer
 
 
 
 
 
 
 
 
 
 

 

3dmax

做者: 1056923207@qq.com
3dmax
ps
ai
 

 

Leapmotion虛擬現實

做者: 1056923207@qq.com
1.下載Leapmotion SDK( https://developer.leapmotion.com/v2
2.拖入到場景中
3.找到預設體的HandController拖到場景中 縮放調爲10
4.運行遊戲 筆記本有攝像頭能夠實現手部識別
5.核心的腳本就是HandController

 

Socket

做者: 1056923207@qq.com
步驟:服務器建立一個套接字。2:綁定一個端口 。3:監聽 lister4:accept
 
 
兩種協議:1.TCP(可靠的協議,例如qq)2.UDP(看視頻)

 

Unity網絡基本知識

做者: 1056923207@qq.com
1:網絡通訊協議
 
2:IP地址
 
 
 
 
NetWork類建立愛你服務器和客戶端:
 
 
 
 
 
 
 
 
 
 

 

Unity高通AR解析步驟

來源網址: http://www.jianshu.com/p/bb9aa8bf2225
做者: 1056923207@qq.com
首頁 專題 下載手機應用
114

簡書

交流故事,溝通想法

Download app qrcode
iOS·  Android

下載簡書移動應用

Download app qrcode
100  做者 欣羽馨予2015.11.02 17:05*
寫了16388字,被87人關注,得到了69個喜歡

Unity高通AR解析(一)

字數852閱讀2874評論7喜歡12

前言

在這個生活方式都突飛猛進的年代,任何的新技術產生都不足爲奇,固然本篇所講的AR(加強現實技術)也並非最新的技術了,目前市面上已經不少AR方面的硬件設備,固然AR技術也日漸成熟。目前,Unity對AR的支持,只有一家——高通,原來還有一家Metaio被Apple收購要如今杳無音訊,暫且不提。高通(Qualcomm)是提供Unity插件開發AR產品的AR公司。本篇咱們就來用高通的插件,來開發一個UnityAR小程序。想學Unity就來藍鷗找我吧

  • 註冊高通帳號,獲取許可證,註冊識別圖
    • 因爲高通的AR技術是不開源的,因此使用的時候還須要註冊許可證號。首先,咱們登陸高通官方網站

      高通AR官網
    • 註冊帳號

      註冊

      註冊界面1(密碼中字母要有大寫有小寫)

      註冊界面2

      註冊界面3

      註冊成功

      郵箱驗證
    • 登陸到高通

      登陸

      登陸成功
    • 下載插件

      下載插件
    • 註冊許可證

      註冊許可證

      填寫項目名稱

      完成許可證註冊

      查看註冊好了的許可證
    • 獲取許可證號

      獲取許可證號,暫時保存起來,一下子會用到
    • 註冊識別圖數據庫

      註冊識別圖數據庫

      建立數據庫

      打開數據庫建立識別圖

      添加識別圖

      添加識別圖成功

      下載數據

      選擇Unity Editor,下載

      下載好了的Package
  • 準備就緒,開始Unity開發
    • 建立工程,導入資源(本例使用Unity5.0.2)

      建立工程

      導入高通插件和剛剛生成的Logo包

      導入成功

      找到ARCamera預設體和TargetImage預設體,導入場景

      刪除MainCamera
    • ARCamera屬性介紹

      VuforiaBehaviour
      1.AppLicenseKey//App許可證號碼
       2.CameraDeviceMode//攝像機設備模式
           MODE_DEFAULT = -1,//默認(默認)
           MODE_OPTIMIZE_SPEED = -2,//速度優化
           MODE_OPTIMIZE_QUALITY = -3//質量優化
       3.Max Simultaneous Tracked Images//最大跟蹤圖片數量
       4.Max Simultaneous Tracked Objects//最大跟蹤對象數量
       5.Delayed Loading Object Data Sets//延遲加載對象數據集
       6.Camera Direction//攝像機方向
           CAMERA_DEFAULT,//默認(默認)
           CAMERA_BACK,//後面
           CAMERA_FRONT//前面
       7.Mirror Video Background//鏡像視頻背景
           DEFAULT,//默認(默認)
           ON,//開啓
           OFF//關閉
       8.World Center Mode//全球中心模式
           SPECIFIC_TARGET,//特定的目標
           FIRST_TARGET,//第一個目標
           CAMERA//攝像機(默認)
       9.Bind Alternate Camera//綁定替代相機
    • 咱們須要的設置

      複製許可證號

      寫入許可證號

      激活對象
    • ImageTarget屬性介紹

      ImageTarget屬性介紹
      1.Type類型
           PREDEFINED,//預約義的(默認)
           USER_DEFINED,//用戶定義的
           CLOUD_RECO//雲偵察的
       2.Data Set//數據集
       3.Image Target//目標識別圖
       4.Width//寬度
       5.Height//高度
       6.preserve child size//保存子對象大小
       7.Extended Tracking//跟蹤拓展
       8.Smart Terrain//智能地形
    • 咱們須要的設置

      選擇數據庫和識別圖
    • 找一個識別後顯示的模型,放置爲ImageTarget的子物體

      放置模型
    • 設置攝像機位置,調整模型縮放

      微調
  • 運行測試

    個人iOS9.1,還沒來得及下Xcode7.1,暫時這樣測試

    結束語

    本篇主要實現基本的AR顯示,後續還會寫後面的高級實現,敬請期待。想學Unity就來藍鷗找我吧

若是以爲個人文章對您有用,請隨意打賞。您的支持將鼓勵我繼續創做!

¥ 打賞支持
12
打開微信「掃一掃」,打開網頁後點擊屏幕右上角分享按鈕
Tiny
Tiny

 

www

做者: 1056923207@qq.com
www的屬性:texture(下載的圖片) audioclip(下載的聲音) movie(下載的視頻) bytes(下載的二進制,把文件以二進制的形式存儲下來)  text isdone (是否下載完成 )progress(下載的進度) URL(下載的地址)
整個代碼全部名字爲www的變量名字的改變:點擊程序中任意一個變量名,而後右鍵重命名 這樣改一個就能夠,程序中全部其餘的都會改變;

 

協程

做者: 1056923207@qq.com
攜程的使用方法:
注意:攜程的方法須要把void換成IEnumerator  而後在Start裏面用startCoroutine()開啓攜程(該方法裏面是攜程的"方法名字」或者以下所示)
 
 
  void  Start()
    {
        StartCoroutine(DownLoadMovia());
    }
     public IEnumerator DownLoadMovia()
    {
         string url = "http://172.18.21.77/aaa.mp4";
         WWW www = new WWW(url);
         yield return www;
    }
 
 
攜程的方法:StartCoroutine(方法);
                    StopCoroutine(方法);
                    Yield return WaitForSeconds(float f);//過f秒再執行後面的代碼;
                     yield return StarCoroutine(otherIEnumerator());//等到括號裏面的攜程執行完畢後 在執行本句後面的代碼;
 
 
攜程的執行順序  在Update和LateUpdate之間;

 

打包

做者: 1056923207@qq.com
 
 
 
數據庫 發佈到安卓:
 
兩個路徑1.當前工程數據庫文件的位置
               2安卓手機上程序的安裝位置(由於;安卓裏沒有數據庫文件。解決方案:放一個數據庫文件進來);
 
 
將數據庫文件放置到安卓手機程序的安裝位置;1
 
1: 解析安裝包apk   拿到數據庫文件  而後放置到安卓手機程序的安裝位置
 
 
兩個語法:
1:安裝包apk路徑語法  jar
2:安卓數據庫連接字符串語法 url
 
發佈到安卓的具體方法:

 

數據庫登陸界面

做者: 1056923207@qq.com
 
 
using  UnityEngine;
using  System.Collections;
using  Mono.Data.Sqlite;
using  UnityEngine.UI;
public  class InputCheck : MonoBehaviour {
 
     public InputField passwordtext;
         // Use this for initialization
         void Start () {
       
       }
       
         // Update is called once per frame
         void Update () {
       
       }
 
     public void CheckUserName()
    {
         string datapath = "Data Source=" + Application .streamingAssetsPath + "/UserDatabase.sqlite" ;
         SqliteConnection userconnect = new SqliteConnection (datapath);
        userconnect.Open();
         SqliteCommand usercommand = userconnect.CreateCommand();
       
         string userstring = transform.GetComponent< InputField>().text;
      
      
        usercommand.CommandText =  "select * from UserTable";
 
        SqliteDataReader  username = usercommand.ExecuteReader();
 
         while (username.Read())
        {
             for ( int i = 0; i < username.FieldCount; i++)
            {
                 //返回值爲object
                 //若是帳號正確
                 if (username.GetValue(i).ToString() == userstring)
                {
                     
                         //判斷密碼是否正確
                         if (username.GetValue(1).ToString() == passwordtext.text)
                        {
                             Debug.Log( "登陸成功" );
                             return;
                        }
                       
                      //密碼不正確 
                     Debug.Log( "密碼錯誤" );      
                     return;
                }
                 else
                {
                     Debug.Log( "帳號不存在" );
                }
            }
        }
       
 
    }
 
 
}

 

SQLite

做者: 1056923207@qq.com
sql語法:
數據庫字符串類型的要用單引號引發來例如:'sadfas'
username.GetValue(i);返回值爲object類型:
 
 
 
示例
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

數據存儲

做者: 1056923207@qq.com
xml的生成與解析:
1:xml的生成:(引入命名空間using System.Xml:xml的生成與解析都用這一個就行)
    //生成xml文件
     public void creatXML()
    {
         //生成xml文件的名稱以及路徑
         string filepath = Application.dataPath + "/Resources/XMLFile1.xml" ;
         //建立一個xml文檔操做對象
         XmlDocument doc = new XmlDocument ();
         //建立一個xml文檔頭
        XmlDeclaration declaration = doc.CreateXmlDeclaration( "1.0", "UTF-8" , null);
         //將xml文檔頭添加到文檔操做對象doc中
        doc.AppendChild(declaration);
         //doc.Save(filepath);
 
 
 
         //建立子節點
 
         //1.建立一個根節點
         XmlElement root = doc.CreateElement("Scene" );
         //2.將根節點添加到文檔中
        doc.AppendChild(root);
         //在根節點下添加一個子節點
         XmlElement child1 = doc.CreateElement("GameObject" );
         //添加給root
        root.AppendChild(child1);
         //添加屬性
         XmlAttribute attr1 = doc.CreateAttribute("Name" );
        attr1.Value =  "Cube";
        child1.SetAttributeNode(attr1);
        child1.SetAttribute(  "sex", "man" );
        child1.SetAttribute(  "Layer", "Water" );
        child1.SetAttribute(  "Tag", "寧" );
 
         //爲GameObject添加子節點
         XmlElement child1_transform = doc.CreateElement("Transform" );
        child1.AppendChild(child1_transform);
 
         //位Transform添加三個子節點x,y,z
         XmlElement child2_position = doc.CreateElement("Position" );
        child1_transform.AppendChild(child2_position);
 
        child2_position.SetAttribute(  "x", "1" );
        child2_position.SetAttribute(  "y", "2" );
        child2_position.SetAttribute(  "z", "3" );
 
 
        doc.Save(filepath);
 
    }
 
生成的結果:
<? xml  version="1.0" encoding =" UTF-8" ?>
< Scene >
  < GameObject  Name="Cube" sex =" man" Layer= "Water " Tag="" >
    <  Transform>
      <  Position x =" 1" y= "2 " z="3" />
    </  Transform>
  </ GameObject >
</ Scene >
 
 
 
2:xml的解析:
 
  //解析xml文檔(其實就是SelectSingleNode函數)
     //public void readxml()
     //{
     //    //實例化一個xml文檔操做類
     //    XmlDocument doc = new XmlDocument();
     //    string xmlfilepath = Application.dataPath + "/Resources/XMLFile1.xml";
     //    //doc.Load(xmlfilepath);
     //    //獲取元素的根節點
     //   XmlElement root = doc.DocumentElement;
     //    //Debug.Log(root.Name);
     //    //篩選節點
     //  XmlNode node1 = root.SelectSingleNode("GameObject");
     //    //sDebug.Log(node1.Name);
     //    XmlAttributeCollection attributes = node1.Attributes;
     //    foreach (var item in attributes)
     //    {
     //        XmlAttribute att = (XmlAttribute)item;
     //        Debug.Log(att.Name +":"+ att.Value);
     //    }
 
 
 
     //    XmlNode node1_transform = node1.SelectSingleNode("Transform");
     //    Debug.Log(node1_transform.Name);
     //    //解析剩下的節點
     // XmlNode xnode = node1_transform.SelectSingleNode("x");
     //    XmlNode ynode = node1_transform.SelectSingleNode("y");
     //    //獲取x節點下的文本內容
     //    Debug.Log(xnode.OuterXml);
     //    Debug.Log(ynode.InnerText);
     //}
 
 
 
要想顯示漢字必須把文件(例如text)格式改成UTF-8的形式;
Json數據生產:
using  UnityEngine;
using  System.Collections;
using  System.Json;//引入命名空間
 
public  class jeson : MonoBehaviour {
 
第一種:
  public  void CreatJsonstr()
    {
         //生成一個Json對象
         JsonObject root = new JsonObject ();
 
        root.Add(  "HeroName", "諾克薩斯之手" );
        root.Add(  "HP", "58.6f" );
         JsonObject skill1 = new JsonObject ();
        skill1.Add(  "skillname", "chuxue" );
        skill1.Add(  "skilltype", "Passive" );
        skill1.Add(  "xiaohao", "9/8/7/6" );
         JsonObject skill2 = new JsonObject ();
        skill2.Add(  "adf", "afdf" );
        skill2.Add(  "sdafa", "iui" );
        skill2.Add(  "aufhuds", "asdfy" );
 
         JsonArray cd = new JsonArray();
        cd.Add(skill1);
        cd.Add(skill2);
        root.Add(  "技能",cd);
      
       string str =   root.ToString();
 
         Debug.Log(root);
 
 
    }
 
 
 
第二種:(不理解)
     JsonObject jo;
         // Use this for initialization
         void Start () {
         //建立一個json對象
        jo =  new JsonObject();//至關於寫好了一個大括號
         //設置一個json值
        JsonValue jv = "10";//int  float  string
         //json對象添加鍵值對
        jo.Add(  "name", jv);
         Debug.Log(jo.ToString());
         //建立一個json數組
         JsonValue[] sons = new JsonValue[] { "masterwang", "oldwang" };
         //實例化一個json數組
         JsonArray arr = new JsonArray(sons);
         //json對象添加對象數組
        jo.Add(  "sons", arr);
         //debug.log(jo.tostring());
        HandOfLittleStudent();
    }
 
 
     void HandOfLittleStudent()
    {
         //建立技能q的Json對象
         JsonObject skillq = new JsonObject ();
         //添加一個技能名稱
        skillq.Add(  "Q", "大廈四方" );
         //建立一個數組對象
         JsonArray cd = new JsonArray( new JsonValue[] { 9, 8, 7, 6, 5 });
 
        skillq.Add(  "冷卻時間" ,cd);
        skillq.Add(  "消耗法力" , 30);
      
        skillq.Add(  "jo", jo);
         Debug.Log(skillq);
    }
   
}
=
 
 
Json數據解析:
using  UnityEngine;
using  System.Collections;
using  LitJson;//引入解析明明空間
public  class litjjjson : MonoBehaviour {
         void Start ()
       {
        ParJson();
       }
     public void ParJson()
    {
//解析第一個文本
TextAsset  jsonfile1 = Resources .Load("transformtext" ) as TextAsset ;
         string jsonstr1 = jsonfile1.text;
         JsonData date1 = JsonMapper.ToObject(jsonstr1);
         Debug.Log(date1[2][ "y"]);
 
 
 
//解析第二個文本;
         //加載文件到text
         TextAsset jsonfile = Resources.Load( "Json") as TextAsset ;
         string jsonstr = jsonfile.text;
       //將text轉換成對象的格式
         JsonData date = JsonMapper.ToObject(jsonstr);
       //輸出skills對象第2個的技能名字
         Debug.Log(date[ "skills"][1]["skillName" ]);
 
    }
 
 
}
 
 
//如何保存成爲一個Json文件
 
 
 
 
 
 

 

粒子特效

做者: 1056923207@qq.com
1:粒子系統
2:拖尾渲染
3:線性渲染
4:貼圖融合
 
1.粒子系統:粒子系統其實就是一個組件:Particle System。
Particle System組件面板以下:
using  UnityEngine;
using  System.Collections;
using  UnityEngine.UI;
 
public  class PlayerprefabsTest : MonoBehaviour {
 
     /// <summary>
     /// 本地數據的存儲測試
     /// </summary>
         // Use this for initialization
     public InputField Leval;
     public InputField Score;
     public InputField Name;
 
 
 
         void Start ()
    {
         //Debug.Log(PlayerPrefs.GetInt("Leval"));
         //Leval.text = PlayerPrefs.GetInt("Leval").ToString();
         //Score.text = PlayerPrefs.GetFloat("Score").ToString();
         //Name.text = PlayerPrefs.GetString("姓名");
       }
       
         // Update is called once per frame
         void Update () {
       
       }
 
     public void savedate()
    {
         PlayerPrefs.SetInt("Leval" , 30);
         PlayerPrefs.SetFloat("Score" , 153.6f);
         PlayerPrefs.SetString("姓名" ,"張大雞復活節第三zhang" );
 
    }
 
 
 
     public void ReadDate()
    {
         string rank = PlayerPrefs.GetInt("Leval" ).ToString();
         float score = PlayerPrefs.GetFloat("Score" );
         string name = PlayerPrefs.GetString("姓名" );
        Leval.text = rank;
        Score.text = score.ToString();
        Name.text = name;
 
    }
     public void clearall()
    {
 
         PlayerPrefs.DeleteAll();
    }
   
 
}

 

PlayerPrefaebs 小型遊戲能夠用:

做者: 1056923207@qq.com
PlayerPrefaebs  小型遊戲能夠用:
 

 

粒子特效

做者: 1056923207@qq.com
1:粒子系統
2:拖尾渲染:Trail Render
3:線性渲染:Line Render
4:貼圖融合
 
1.粒子系統:粒子系統其實就是一個組件:Particle System。
Particle System組件面板以下:
 
線性渲染:
 
 
 
 
 
貼圖融合:例如製做彈痕效果 :
 
 
 
 

 

導航

做者: 1056923207@qq.com
步驟 :
1:將想要烘焙的場景裏的物體選中  而後Static裏面選中NavigationStatic(導航靜態);
NavMeshAgent組件的屬性,方法:
NavMeshAgent  nav ;
float dis = nav.remainingDistance;
float  sdis = nav.StoppingDistance;
nav.updatePosition=false;那麼遊戲對象的座標固定不變;
nav.updateRotation=false;那麼遊戲對象的旋轉固定不變:
nav.Stop();//中止導航
 
首先在Windows窗口添加一個Navigation  在該面板設置相應的參數;
注意:上圖左側選中環境裏須要烘焙的物體,右側Object面板要選中Navigation Static(打上對勾);
 
Bake界面:設置相應的參數;
 
 
遊戲主角:添Nav Mesh Agent組件,這個組件是用來導航的 添加了這個組件才能夠調用他的函數,好比setdestination等封裝好的函數,以下圖;
 
Area Mask組件:能夠選擇讓組件掛在的遊戲對象選擇走那些路  不走哪些路;(分層);
 
 
 
 
 
 
 
分離路面導航:
 
分離路面導航在組件:Off Mesh Link
組件的使用方法:在兩個點上的一個掛上該組件就行,而後將兩個物體拖進組件中;(該組件不是放在遊戲主角上,而是放在環境物體身上);
首先:
 
 
而後:
 
 
 
分層烘焙路面:
 
下圖中Cost的值越小  優先級越高,相同條件下,主角會從該層行走。
 
在object面板設置層:以下圖
主角設置爲Walkbale 表明全部的層均可以走,
環境信息設置爲另外一個層 好比road1 (有一個Cost值 表明了該層的優先級);
 
除了手動選擇層外,還能夠用代碼實現:以下
 
動態障礙:
 
動態障礙功能實現的組件:Nav Mesh Obstcal,
 
面板以下層:
 
 
 

 

關於射線的筆記

做者: 1056923207@qq.com
  RaycastHit  rrr;
  Ray  hit = Camera.main.ScreenPointToRay( Input.mousePosition);
  Physics .Raycast(hit,  out rrr);
上述代碼能夠獲得鼠標點擊點的信息,rrr.point是一種position類型;

 

動畫系統2

做者: 1056923207@qq.com
動畫層:
 
Mask:遮罩  在JumpLayer加avator Mask (設置一下),權重weight 要設置爲1;
IK Pass 勾上表明可使用IK;
 
Avatar Mask組件;
 
 
IK動畫的使用:
1:只有人型動畫才能設置IK;
1:裏面的權重(1f)表示任務擡手動做的大小,0表明不擡手,1表明徹底指向目標:
2:將手指向,轉向rightHandObj對象;(與lookat很類似);
3:若是沒有rightHandobj這個對象,則手不進行任何操做;
 
 
 
 
 
 
 
動畫曲線:若是動畫曲線叫Curve(以下圖),那麼在parameter面板加一個一樣名字的Float變量(這個變量的值隨着圖Curve的變化而變,大小同樣),在腳本里利用GetFloat方法獲取曲線的y值進行利用;
 
 
 
 
動畫事件:Event;
 
 
 
 
下圖是在Idle Walk 等動畫裏設置的 不是人物裏面設置的;
 
 
 
 
注意:下圖Object參數必須是一個預設體:
 
 
 
腳本必須放在人物身上,不是動畫身上;
 
 
 

 

動畫系統一

做者: 1056923207@qq.com
一:mecanim動畫系統:]
1:任性動畫設置和重用;
2:動畫剪輯設置
3;可視化動畫控制界面
4:動畫播放的精準控制
 
動畫類型:無任何動畫  legacy 舊版動畫 Generic 通常動畫(非人性動畫) Humanoid 人形動畫
 
人性動畫設置:
 
 
測試骨骼:肌肉測試
 
點擊Done 回到正常界面
 
 
點擊Import 若是現實下面的內容說明該模型沒有動畫;
 
模型沒有動畫的時候:Animations面板
 
模型有動畫時的Animations面板:
 
把模型所包含的動畫剪輯成的片斷:點擊+號能夠添加剪輯片斷-好能夠刪除選中的片斷
 
動畫剪輯面板:
 
 
動畫編輯:
 
loop Time  讓動畫循環執行:
Loop Pose 讓動畫起始幀和末尾幀銜接更加天然,動畫更加流暢;
Cycle Offset 設置動畫開始執行的幀位置:
Loop Match  紅色表明動畫不能播放;黃色不能順暢的播放;綠色能夠;
 
Bake Into pose;烘焙進姿式:只有動做(例如動畫有旋轉的動做,可是座標不改變,線面兩個位移也是同樣) 沒有位移:
 
 
注意上面的Cycle Offset 和下面的Offset是不同的 下面表明的是位置的便宜  上面表明的是動畫整形循環的開始的幀位置:
 
mirror:當前動畫是按照原動畫執行動做,仍是鏡像裏的動畫執行動做:
 
 
 
 
Animator組件:
Controller:動畫控制器
Avator:人物骨骼(阿凡達);
Apply Root motion :只有勾選上,在動畫設置裏的改動才能應用,不然用的是原版動畫,全部更改都沒用啦;
Culling Mode :時間縮放;
Update:動畫顯示更新模式;
 
 
 
二State Machine狀態機:
 
 
 
 
 
 
 
 
三:Blend Tree:融合樹:

 

動畫系統一

做者: 1056923207@qq.com
一:mecanim動畫系統:]
1:任性動畫設置和重用;
2:動畫剪輯設置
3;可視化動畫控制界面
4:動畫播放的精準控制
 
動畫類型:無任何動畫  legacy 舊版動畫 Generic 通常動畫(非人性動畫) Humanoid 人形動畫
 
人性動畫設置:
 
 
測試骨骼:肌肉測試
 
點擊Done 回到正常界面
 
 
點擊Import 若是現實下面的內容說明該模型沒有動畫;
 
模型沒有動畫的時候:Animations面板
 
模型有動畫時的Animations面板:
 
把模型所包含的動畫剪輯成的片斷:點擊+號能夠添加剪輯片斷-好能夠刪除選中的片斷
 
動畫剪輯面板:
 
 
動畫編輯:
 
loop Time  讓動畫循環執行:
Loop Pose 讓動畫起始幀和末尾幀銜接更加天然,動畫更加流暢;
Cycle Offset 設置動畫開始執行的幀位置:
Loop Match  紅色表明動畫不能播放;黃色不能順暢的播放;綠色能夠;
 
Bake Into pose;烘焙進姿式:只有動做(例如動畫有旋轉的動做,可是座標不改變,線面兩個位移也是同樣) 沒有位移:
 
 
注意上面的Cycle Offset 和下面的Offset是不同的 下面表明的是位置的便宜  上面表明的是動畫整形循環的開始的幀位置:
 
mirror:當前動畫是按照原動畫執行動做,仍是鏡像裏的動畫執行動做:
 
 
 
 
Animator組件:
Controller:動畫控制器
Avator:人物骨骼(阿凡達);
Apply Root motion :只有勾選上,在動畫設置裏的改動才能應用,不然用的是原版動畫,全部更改都沒用啦;
 
 
 
二State Machine狀態機:
 
 
 
 
 
 
 
 
三:Blend Tree:融合樹:

 

動畫的遮罩

做者: 1056923207@qq.com
狀態機作兩個層  在第二個層里加上AAnimatorMask 而且把他的Weight設置爲1,兩個層的頁面以下:
基層:
 
 
 
 
另外一層:正常狀態不是Idle  而是New State(空狀態)

 

單例類

做者: 1056923207@qq.com
單例的缺點:沒有繼承各類類和MoNo;unity的封裝方法沒辦法用,部分可使用(gameobject,tansform)若是用到了MONO的方法會異常處理(一些重要的代碼用到,尤爲是用戶交互);
 
單利類不放在任何組件對象身上,可是單利腳本(繼承mono)必須放在對象身上;
 
 
 
單利類:
 
public class SImpple
{
     private SImpple()
    {
 
 
    }
 
     private static SImpple _instanse;
 
     public static SImpple getinstanse()
    {
         if (_instanse == null)
        {
            _instanse =  new SImpple();
        }
      
       
             return _instanse;
    }
       
}
 
 
單例腳本
單利腳本的缺點,在切換場景的時候容易被銷燬(解決辦法:使用DontDestroyThis()方法防止單例腳本被銷燬);
 
 
using  UnityEngine;
using  System.Collections;
 
public  class SingleScript : MonoBehaviour
{
     public static SingleScript _instance;
 
     void Awake()
    {
        _instance =  this;
 
    }
       
}
 
 

 

單例類

做者: 1056923207@qq.com
單例的缺點:沒有繼承各類類和MoNo;unity的封裝方法沒辦法用,部分可使用(gameobject,tansform)若是用到了MONO的方法會異常處理(一些重要的代碼用到,尤爲是用戶交互);
 
單利類不放在任何組件對象身上,可是單利腳本(繼承mono)必須放在對象身上;
 
 
 
單利類:
 
public class SImpple
{
     private SImpple()
    {
 
 
    }
 
     private static SImpple _instanse;
 
     public static SImpple getinstanse()
    {
         if (_instanse == null)
        {
            _instanse =  new SImpple();
        }
      
       
             return _instanse;
    }
       
}
 
 
單例腳本
using  UnityEngine;
using  System.Collections;
 
public  class SingleScript : MonoBehaviour
{
     public static SingleScript _instance;
 
     void Awake()
    {
        _instance =  this;
 
    }
       
}
 
 

 

EventSystem

做者: 1056923207@qq.com
一:添加 Event Trriger組件  不用寫代碼;
二:寫代碼以下:注意引入事件系統;實現接口繼承
三:實現UI明明空間;(看start裏面的方法,不能寫在Update裏面,只註冊一次就行),須要給腳本託一個腳本組件;
 
 
 
 
 
 
using  UnityEngine;
using  System.Collections;
using  UnityEngine.EventSystems;
using  System;
using  UnityEngine.UI;
 
public  class EventSystomText : MonoBehaviour,IPointerEnterHandler ,IPointerExitHandler ,IPointerDownHandler ,IPointerUpHandler ,IPointerClickHandler ,IBeginDragHandler ,IDragHandler ,IEndDragHandler ,
{
//第三種方法的代碼
     public Button btn;
 
     public void OnBeginDrag( PointerEventData eventData)
    {
         Debug.Log( "開始拖拽" );
         //throw new NotImplementedException();
    }
 
     public void OnDrag(PointerEventData eventData)
    {
         Debug.Log( "正在拖拽" );
         //throw new NotImplementedException();
    }
 
     public void OnEndDrag( PointerEventData eventData)
    {
         Debug.Log( "結束拖拽" );
         //throw new NotImplementedException();
    }
 
     public void OnPointerClick( PointerEventData eventData)
    {
         Debug.Log( "鼠標點擊" );
        // throw new NotImplementedException();
    }
 
     public void OnPointerDown( PointerEventData eventData)
    {
         Debug.Log( "鼠標按下" );
         //throw new NotImplementedException();
    }
 
     public void OnPointerEnter( PointerEventData eventData)
    {
         Debug.Log( "shubiaojinre");
        // throw new NotImplementedException();
    }
 
     public void OnPointerExit( PointerEventData eventData)
    {
         Debug.Log( "鼠標離開" );
         //throw new NotImplementedException();
    }
 
     public void OnPointerUp( PointerEventData eventData)
    {
         Debug.Log( "鼠標擡起" );
        // throw new NotImplementedException();
    }
 
//第三種方法的代碼
     public void Res()
    {
 
 
    }
 
     // Use this for initialization
     void Start () {
//只執行一次就行
        btn.onClick.AddListener(Res);
       
       }
       
         // Update is called once per frame
         void Update () {
       
       }
}

 

場景的加載

做者: 1056923207@qq.com
        //1.讀取新的關卡後當即切換,其參數爲所讀取的新關卡的名稱或索引;
         Application.LoadLevel("your scene" );
         //2.加載一個新的場景,當前場景不會被銷燬。
         Application.LoadLevelAdditive("Your scene" );
 
 
 
         //異步加載場景
         //1.加載完進入新場景銷燬以前場景
         Application.LoadLevelAsync("Your Scene" );
         //2.加載完畢進入新場景可是不銷燬以前場景的遊戲對象
         Application.LoadLevelAdditiveAsync("Your Scene" );

 

Application(應用程序)

做者: 1056923207@qq.com
做用:1.加載遊戲關卡場景
          2.獲取資源文件路徑
          3.退出當前遊戲場景
          4.獲取當前遊戲平臺
          5.獲取數據文件夾路徑
 
Application.Plateform  返回值爲當前程序運行所在的平臺;
  Debug .Log( Application .runInBackground);可讀可寫,返回程序是否在後臺運行的布爾值:
 
 
Application類的測試:
 
 
     void Start()
    {
         //打印在哪一個平臺運行
         Debug.Log( Application.platform);
         //返回是否在後臺運行(bool值)
         Debug.Log( Application.runInBackground);
         //當前工程的Assets文件夾位置(僅編輯器有);
         Debug.Log( Application.dataPath);
         //持久路徑
         Debug.Log( Application.persistentDataPath);
         //數據流路徑
         Debug.Log( Application.streamingAssetsPath);
         //返回當前場景的索引號
         Debug.Log( Application.loadedLevel);
       
    }
 
 
輸出結果:
 

 

坦克轉向鼠標的位置

做者: 1056923207@qq.com
鼠標的位置轉換成世界座標: Vector3 WorldPoint =Camera.main.screenToWorldPoint(mousePoint);
Vector3 direction =worldPoint -mGunTransform.position;
mGunTransform.rotation=Quternion.LookRotation(Vector3.forword,direction)
 

 

實現小地圖的方法

做者: 1056923207@qq.com
在已經建立好的ui界面:首先議案家一個攝像機,而後將主攝像機的層級設置爲1(大於新添加的攝像機),在建立一個Render Texture組件,建立一個RawImage組件,將該組件的北京圖片換爲剛纔建立的Render Texture便可;
 
若是小地圖裏面物體的移動方向與主場景中的不一致,能夠在sence裏面調整新添加的相機的視角;
 
怎樣實現小地圖攝像機跟隨某個物體移動:把小地圖攝像機設置爲想要跟隨的目標的子物體就行:
 
實現小地圖不顯示實際的任務,只顯示人物頭像(相似lol小地圖):添加一個Canvas(Render Mode設置成世界模式(World Space),Event Camera設置成小地圖的相機(渲染的時候將人物層剔除掉,主相機則是將人物頭像(新建一個層,不能是原來的ui層)層剔除掉),將人物頭像與任務xz座標調成一致,)

 

添加遮罩

做者: 1056923207@qq.com
1.添加一個RawImage組件,背景圖片選一張你想要顯示的形狀的無色的圖片,在該組件上再添加一個Mask組件,將要顯示的通篇放到該RawImage組件上;

 

血條,頭像

做者: 1056923207@qq.com
遮罩:在父物體上添加Mask,在給其添加一個形狀,在添加一個子物體圖片,子物體的圖片就會隨着形狀的改變而改變;

 

UGUI

做者: 1056923207@qq.com
Image組件:Image Type 能夠作不一樣的功能;
 

 

Sprite

做者: 1056923207@qq.com
1,2D遊戲相機設置爲正交相機 size:5
2.資源切圖
3.遊戲背景設置成:在game視圖中設置爲Free Aspect;(自適應屏幕大小)
4.預製體的建立:炮口,炮彈,魚;

 

2D動畫的建立

做者: 1056923207@qq.com
選中切割好的圖片,所有選中拖到Hierirychy面板中,給個動畫名字,而後直接播放便可,也能夠拖成預製體,

 

世界座標與本地座標的轉換

做者: 1056923207@qq.com
將屏幕左邊轉換成世界座標;transform.postion = Camera.main.ViewportToWorldpoint(Input.mouseposition);
 
                                         
 transform.position =  Camera.main.ViewportToWorldPoint( new Vector3(Input .mousePosition.x / Screen.width, Input.mousePosition.y / Screen.height, 4));

 

2D圖片處理

做者: 1056923207@qq.com
若是不在工程設置裏Edtor更改設置(DisAble,Enable forbuildings,Always Enable),那麼系統會自動打包圖片(即講多張圖片放到一張圖片中)。
從一張打包好的圖片裏切割出小圖片的好處:下降 CPU 的 DrawCall  切割出來的圖片都算做一次Drawcall;
處理修改圖片的組件:Sprite Renderer;
快速進入API:點擊組件右側的小問號。

 

觸發器

做者: 1056923207@qq.com

 

碰撞器

做者: 1056923207@qq.com
1.碰撞器的大小能夠人爲地改變,來適應需求;
2.碰撞器的類型:膠囊體碰撞器,圓形碰撞器(2D)
3.OnCollisionEnter等回調方法須要有剛體;
4.GetComponent<MeshRenderer>().material.color=Color.red=new Color(255,0,0);兩種方式是等價的;         能夠改變物體的顏色;
 

 

對遊戲對象的測速

做者: 1056923207@qq.com
1.兩個觸發器:一個觸發器檢測到車的觸發器後繼而拿到其剛體組件繼而拿到其速度:

 

Transform類

做者: 1056923207@qq.com
靜態類:Time.time  遊戲從開始到如今運行的時間;
 
Vector3是一個結構體,經常使用屬性:vector3.normalied:標準化向量 方向不變,長度爲1;
                                   vector3.magnitude  向量的長度(只讀);
                                   vector3.sqrMagnitude:向量長度平方(只讀);
                                    經常使用方法:vector3.Normalied():標準化向量,長度爲1
                                                    static float Angle(Vector3 from,vector3 to);兩向量之間的角度
                                                    static float Distance(Vector a,Vector3 b);兩點之間的距離
 
 
transform.rotation = Quaternion.look(vector3.left,vector.up);
 
子彈飛行:子彈上的腳本Update裏:
 transform.Translate( Vector3 .forward*  Time.deltaTime*speed);
 
設置父對象:bullet.transform.parent=parent.transform;===bullet.transform.setparent(parent.transform);
經過設置Transform父子關係能夠在敵人指定的部位產生爆炸流血特效;
 
float v =Input.Getaxis("Horizontal");  v是一個0到1之間的值
 
物體自轉的公式;
transform.Rotate(transform.up *  Time.deltaTime * Rspeed*hor);

 

7.13筆記 unity組件

做者: 1056923207@qq.com
一個遊戲物體身上有不少的組件:
銷燬遊戲對象的兩種方式:1,Destroy();繼承MonoBehavior類
transform.Translate(vector3.up);改變的是本地座標。
transform.position+=vector3.up;改變的是世界座標。
transform.Rotate(vector3.up);
translate.RotateArround(new Vector3(0,0,0),Vector3.up,10(旋轉角度,並非速度。可是放到Update每秒執行多少次,其值的大小就能夠表明速度啦));
transform.LookAt(Target.Transform);讓當前腳本掛載的物體朝向目標可是不移動;
Target.transform.localscale=new vector(2,2,2);   改變Target的縮放。
 

 

關於射線的知識點

做者: 1056923207@qq.com
Debug.Draw()方法是持續執行的必須放在update()裏面才能看到劃線,並且只能在Scene裏面才能看到在Game視圖看不到;
 
代碼以下:
public  class CameraRay : MonoBehaviour
{
     RaycastHit Hit;
     void Start()
    {
         bool isRaycast = Physics.Raycast( new Vector3(0, 1, 0), Vector3.down, out Hit);
 
         if (isRaycast)
        {
             Debug.Log(Hit.point);
        }
    }
 
     void Update()
    {
 
         Debug.DrawLine( new Vector3(0, 10, 0), Hit.point, Color.red);
 
    }
 
 
}

 

關於物體的移動

做者: 1056923207@qq.com
若是想讓物體的速度由快到慢:就用lerp函數:transform.position=vector3.Lerp(transform.position,Target,Time.delTime);
 
第二種移動方法:      float hor= Input.GetAxis("Horizontal");
                                float ver = Input.GetAxis("Vertical");
                                transform.position +=new Vector3(hor,ver,0)*Time.delTime;
 
 
 
第二種方法的第二種寫法:      float  hor = Input .GetAxis("Horizontal" );
                          transform.position += transform.right * hor *  Time.deltaTime * speed;

 

尋找當前腳本掛在物體的子物體

做者: 1056923207@qq.com
point= transform.Find("Gun/Point");

 

紋理和材質球通常是配合使用的;想要變得更逼真,就把貼圖變成map的

做者: 1056923207@qq.com
紋理和材質球通常是配合使用的;想要變得更逼真,就把貼圖變成map的

 

射線的建立

做者: 1056923207@qq.com

 

鼠標拖拽物體

做者: 1056923207@qq.com
using  UnityEngine;
using  System.Collections;
 
public  class Script1 : MonoBehaviour
{
     public float movespeed;
     private Vector3 PresentPosition;
     private Vector3 CurrentPosition;
     void OnMouseDown()
    {
        PresentPosition=  Input.mousePosition;
 
    }
 
     void OnMouseDrag()
    {
        CurrentPosition =  Input.mousePosition;
         Vector3 dir = CurrentPosition - PresentPosition;
        transform.position += dir*movespeed;
        PresentPosition = CurrentPosition;
 
 
 
 
    }
 
 
     void Update()
    {
        OnMouseDown();
        OnMouseDrag();
 
    }
 
 
       
}

 

10抽象類,靜態類

做者: 574096324@qq.com
 
         //若是一個方法前面用abstruct來修飾,改方法爲抽象方法,同時須要把該抽象方法所在的類改成抽象類
         //全部的子類都要把父類的抽象方法重寫,若是父類裏面有多個抽象方法,則必須實現
         //抽象類不能實例化,他能夠用普通的子類進行實例化
         //抽象類裏面能夠不包含抽象方法,此時除了不能實例化之外,和普通的類沒有任何區別
         //若是子類儀式抽象類,能夠不用實現父類裏面的抽象方法
         public abstract void Train();
         public string Name { get; set; }
         public void Run()
        {
 
        }
    }
     abstract class Person
    {
         public string Name { get; set; }
         public void Talk()
        {
 
        }
    }
     class FootballPlayer : Athlete
    {
         public override void Train()
        {
             Console.WriteLine("足球運動員訓練" );
        }
    }
     abstract class ManFootball :FootballPlayer
    {
         public override void Train()
        {
 
        }
    }
     class Swimmer: Athlete
    {
         public override void Train()
        {
             Console.WriteLine("游泳運動員訓練" );
        }
    }
     class Runner: Athlete
    {
         public override void Train()
        {
             Console.WriteLine("短跑運動員訓練" );
        }
    }
     abstract class Ball
    {
         public abstract void Play();
    }
     class Basketball : Ball
    {
         public override void Play()
        {
             Console.WriteLine("打籃球" );
        }
    }
     class Football : Ball
    {
         public override void Play()
        {
             Console.WriteLine("踢足球" );
        }
    }
     class Volleyball : Ball
    {
         public override void Play()
        {
             Console.WriteLine("打排球" );
        }
    }
單例
class  Hero
    {
           //1.要保證該類只能建立出一個對象,則構造方法就不能爲公有的,這樣就能夠在類的內部建立出一個對象
         //而後經過屬性在類的外部獲得該對象
         private Hero()
        {
 
        }
         //2.在類的內部聲明一個Hero的對象,但不賦值,即沒有new運算符在內存中開闢空間,此時其值爲空
         private static Hero instance;
         //3.因爲構造方法爲私有的,類的外部不能建立對象來調用普通的屬性,故把屬性寫成靜態的,經過類名來調用該屬性
         //而靜態屬性只能調用靜態成員,故要把instance寫成靜態的
         public  static  Hero Instance
        {
             get
            {
               //判斷instance是否爲空,當第一次調用時其值爲空,則執行if語句,就會建立一個對象出來,當第二次調用時,
               //instance已經不爲空,if語句就不會執行了,會把第一個建立的對象返回出去,這樣就保證了該類的對象時惟一的一個
                 if (instance==null )
                {
                    instance =  new Hero ();
                }
                 return instance;
            }
        }
    }

 

枚舉,結構體

做者: 574096324@qq.com
結構體數組結合
找最大最小值,先定義一個max,與max比較,一次循環
排序,冒泡,兩次循環,i<length-1,j<length-1-i,
按年齡排序,要交換整個Student 類型的temp;
 
  int c = char.Parse(Console.ReadLine());
            PlayerStatus player = (PlayerStatus)c;
             PlayerStatus player = (PlayerStatus )char.Parse( Console .ReadLine());
             Console .WriteLine(player);
 
 
             //StuInfos[] stu = new StuInfos[5];
             //double maxScore = stu[0].score;
             //int maxIndex = 0;
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    StuInfos s;
             //    Console.WriteLine("請輸入第{0}個學生的姓名:", i + 1);
             //    string inputName = Console.ReadLine();
             //    s.name = inputName;
             //    Console.WriteLine("請輸入第{0}個學生的年齡:", i + 1);
             //    int inputAge = int.Parse(Console.ReadLine());
             //    s.age = inputAge;
             //    Console.WriteLine("請輸入第{0}個學生的學號:", i + 1);
             //    int inputNumber = int.Parse(Console.ReadLine());
             //    s.number = inputNumber;
             //    Console.WriteLine("請輸入第{0}個學生的分數:", i + 1);
             //    double inputScore = double.Parse(Console.ReadLine());
             //    s.score = inputScore;
             //    //把變量s存到stu的數組裏面
相關文章
相關標籤/搜索