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的使用

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

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

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

     User _user=new User();      

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

              Console.WriteLine("{0}",tmp); //這時tmp的值為“在這里面賦值了”

              Console.ReadKey(true);

   }

     }

  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中的指針變量。它們的區別是:

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

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

3、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)

經常會用到 某個物體的世界坐標到屏幕坐標的轉化然后再屏幕上繪制出這個物體的代表性圖片

是這樣做的

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

2、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的數組里面
             //    stu[i] = s;
             //}
             ////把數組打印出來
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    Console.WriteLine("{0},{1},{2},{3}", stu[i].name,
             //        stu[i].age, stu[i].number, stu[i].score);
             //}
             ////找數組里面的最大分數值
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    if (maxScore < stu[i].score)
             //    {
             //        maxScore = stu[i].score;
             //        maxIndex = i;
             //    }
             //}
             //Console.WriteLine("最高分數是{0}", maxScore);
             //Console.WriteLine("該分數對應的學生信息是:");
             //Console.WriteLine("{0},{1},{2},{3}", stu[maxIndex].name,
             //    stu[maxIndex].age, stu[maxIndex].number, stu[maxIndex].score);
             //for (int i = 0; i < stu.Length - 1; i++)
             //{
             //    for (int j = 0; j < stu.Length - 1 - i; j++)
             //    {
             //        //比較數組元素的年齡的大小
             //        if (stu[j].age < stu[j + 1].age)
             //        {
             //            //交換的時候,是要把整個元素進行交換
             //            //不能只交換數組元素的某一個值,而數組
             //            //里面的元素類型是StuInfos類型
             //            //故要定義一個該類型的中間變量來
             //            //進行交換
             //            StuInfos temp = stu[j];
             //            stu[j] = stu[j + 1];
             //            stu[j + 1] = temp;
 
             //        }
             //    }
             //}
             ////把數組打印出來
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    Console.WriteLine("{0},{1},{2},{3}", stu[i].name,
             //        stu[i].age, stu[i].number, stu[i].score);
             //}
 
             ////找數組里面的最大值
             //double maxScore = stu[0].score;
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    Console.WriteLine("{0},{1},{2},{3}", stu[i].name,
             //        stu[i].age, stu[i].number, stu[i].score);
             //}
             ////找數組里面的最大分數值
             //int maxIndex = 0;
             //for (int i = 0; i < stu.Length; i++)
             //{
             //    if (maxScore < stu[i].score)
             //    {
             //        maxScore = stu[i].score;
             //        maxIndex = i;
             //    }
             //}
             //Console.WriteLine("最高分數是{0}", maxScore);
             //Console.WriteLine("該分數對應的學生信息是:");
             //Console.WriteLine("{0},{1},{2},{3}", stu[maxIndex].name,
             //    stu[maxIndex].age, stu[maxIndex].number, stu[maxIndex].score);
 
             //for (int i = 0; i < stu.Length-1; i++)
             //{
             //    for (int j = 0; j < stu.Length-1-i; j++)
             //    {
             //        if (stu[j].age < stu[j + 1].age)
             //            Student temp = stu[j];
 
             //            stu[j] = stu[j + 1];            //        {
             //            stu[j + 1] = temp;
             //        }
             //    }
             //}

 

字符串,重載,遞歸

作者: 574096324@qq.com
字符串        
   //string str = "lanou,keji,hello/world$bie";
            //string str1 = str;
            //str1 = "keji";
            //Console.WriteLine(str+str1);
檢測字符串中是否包含指定的字符串
            //bool b = str.Contains('a');
            //Console.WriteLine(b);
返回字符串中首次出現指定字符的下標位置
            //int i = str.IndexOf('l');
            //Console.WriteLine(i);
返回字符串中最后次出現指定字符的下標位置
            //int j = str.LastIndexOf('l');
            //Console.WriteLine(j);
左對齊
            //string str1 = str.PadLeft(30);
            //Console.WriteLine(str1);
右對齊
            //string str2 = str.PadRight(30);
            //Console.WriteLine(str2);
從指定下標位置刪除后面的字符串
            //string str3 = str.Remove(10, 5);
            //Console.WriteLine(str3);
替換指定子字符或字符串
            //string str4 = str.Replace("bei", "beijing");
            //Console.WriteLine(str4);
使用指定的字符標志來分割字符串,獲得子字符串
            //char[] c = new char[] { ',' };
            //string[] str5 = str.Split(c);
            //Console.WriteLine(str5.Length);
            //foreach (string item in str5)
            //{
            //    Console.WriteLine(item);
            //}
轉成大寫
            //Console.WriteLine(str.ToUpper());
            //string str7 = str.Trim(' ');
            //Console.WriteLine(str7);
從給定下標位置輸出后面的字符串
            //string str8 = str.Substring(3, 5);
            //Console.WriteLine(str8);
方法的重載
1.方法名相同
2.參數不同 ( 1)參數類型不同  (2)參數個數不同
 
遞歸
public  double Sum(int n)
        {
           
             if (n==1)
            {
                 return 1;
            }
             return Sum(n - 1)+n;
        }

 

異常捕捉

作者: 1056923207@qq.com
如果try里面有錯誤就執行catch里面的代碼,否則不執行catch;但是不管try里面有沒有錯誤都會執行finally里面的內容;
 
try{
int a = int.Parse(Console.ReadLine());
}
catch{
Console.Write("成功的捕捉到了異常");
 
}finally{
 a=1;
}

 

13委托 事件

作者: 574096324@qq.com
課堂練習
using  System;
using  System.Collections.Generic;
 
namespace  Lesson13_3
{
 
                  //張三:初版按鈕的實現
                  /*class Button
                {
                                
                                public string BtnName { get; set;}
 
                                public Button(string btnName){
                                                BtnName = btnName;
                                }
 
                                public void Onclick(){
                                                Console.WriteLine (BtnName+ ":被點擊了");
                                                if (BtnName == "登錄") {
                                                                LoginPageLogic logic = new LoginPageLogic ();
                                                                logic.Login ();
                                                } else if (BtnName == "取消") {
                                                                LoginPageLogic logic = new LoginPageLogic ();
                                                                logic.CancelLogin ();
                                                }
                                }
 
                                public void Onclick(Hero h){
                                                if (BtnName == "a1") {
                                                                h.LeftAction ();
                                                }
                                }
                }*/
                  //張三:委托版按鈕的實現
                  class Button
                {
                                  //定義一個按鈕委托
                                  public delegate void OnclickHandler ();
                                  //定義一個委托變量,用來存放點擊操作的具體方法
                                  public OnclickHandler oncliAction;
 
                                  public void AddOnclickAction(OnclickHandler param){
                                                oncliAction = param;
                                }
 
                                  public string BtnName { get; set;}
 
                                  public Button(string btnName){
                                                BtnName = btnName;
                                }
 
                                  //按鈕點擊的時候調用的方法
                                  public void Onclick(Action< string> callBack){
                                                  Console.WriteLine (BtnName+ ":被點擊了" );
 
                                                  if (oncliAction != null ) {
                                                                  //執行委托
                                                                oncliAction ();
                                                }
 
                                                  if (callBack != null ) {
                                                                callBack (BtnName);
                                                }
                                }
                }
 
                  //李四:登錄頁面邏輯
                  class LoginPageLogic {
                                  public void Login(){
                                                  Console.WriteLine ("登錄成功" );
                                }
 
                                  public void CancelLogin(){
                                                  Console.WriteLine ("取消登錄" );
                                }
                }
 
                  //王二: 英雄類
                  class Hero
                {
                                  public string HeroName{ get; set;}
 
                                  public void LeftAction(){
                                                  Console.WriteLine (HeroName+" 正在犀利的向左走位" );
                                }
 
                                  public void RightAction(){
                                                  Console.WriteLine (HeroName+" 正在犀利的向右走位" );
                                }
                }
 
                  class PrintTool {
                                  //定義一個判斷字符串是否相等的方法委托
                                  public delegate bool StringIsEquals( string str1,string str2);
 
                                  public static void PrintIntArr( int[] arr){
                                                  foreach (int item in arr) {
                                                                  Console.WriteLine (item);
                                                }
                                }
                                  //判斷兩個字符串是否相等的方法
                                  public bool ArrayisEquals(string str1, string str2){
                                                  /*if (str1 == str2) {
                                                                return true;
                                                } else
                                                                return false;*/
                                                  return str1 == str2;
                                }
                }
 
                  class MainClass
                {
                                  public static void Main ( string[] args)
                                {
                                                  //委托的定義格式:
                                                  //訪問修飾符  delegate 返回值類型 委托名稱 (參數列表)
                                                  //訪問修飾符           返回值類型 方法名稱 (參數列表)
 
                                                  //委托的用法:
                                                  //1、聲明委托
                                                  VoidFunction action;
                                                  //2、綁定委托
                                                  //   1.直接賦值
                                                  //action = EngGreeting;
                                                  //   2.通過new關鍵字來初始化綁定
                                                action =  new VoidFunction (EngGreeting);
                                                  //3、調用(和方法的調用類似)
                                                  //action ("張三");
                                                  //4、多播委托,可以將多個方法通過+=運算符綁定到一個委托上
                                                  //   調用委托的時候,會將委托上綁定的方法分別執行
                                                action += ChineseGreeting;
                                                action ( "李四"  );
 
                                                  //1、綁定實例對象的方法
                                                  /*PrintTool print = new PrintTool ();
                                                //聲明委托
                                                Print printArr = new Print (print.PrintIntArr);
                                                int[] result = new int[6]{ 1,2,3,4,5,6};
                                                printArr (result);*/
 
                                                  //2、
                                                  int[] arr = new int[5]{ 1,2,3,4,5};
                                                  Print printArr = new Print ( PrintTool.PrintIntArr);
                                                printArr (arr);
 
                                                  PrintTool tool = new PrintTool ();
                                                  PrintTool.StringIsEquals isEquals = new PrintTool. StringIsEquals (tool.ArrayisEquals);
                                                  bool result = isEquals ("a" ,"a");
                                                  Console.WriteLine (result);
 
                                                  List<int > arrlist = new List< int> ();
                                                arrlist.Add (2);
                                                arrlist.Add (1);
                                                arrlist.Add (5);
                                                arrlist.Add (3);
                                                arrlist.Sort ();
                                                  foreach (var item in arrlist) {
                                                                  Console.WriteLine (item);
                                                }
                                                  Console.Clear ();
 
                                                  //合並委托: 如果委托有返回值,那么返回值就是最后綁定的方法的返回值
                                                  Addelegate del = Add;
                                                del += Mul;
                                                  int result1 = del (2,3);
                                                  Console.WriteLine (result1);
 
                                                  //解除綁定:注意委托不能為null
                                                del -= Mul;
                                                del -= Mul;
                                                  //del -= Add;
                                                  Console.WriteLine (del(2,3));
 
                                                  //登錄,取消頁面邏輯
                                                  LoginPageLogic page = new LoginPageLogic ();
 
                                                  //登錄按鈕
                                                  Button loginBtn = new Button ( "登錄");
                                                  //為登錄按鈕綁定登錄邏輯
                                                loginBtn.AddOnclickAction (page.Login);
                                                loginBtn.Onclick ( delegate ( string  message){
                                                                  Console.WriteLine (message);
                                                });
 
                                                  //為取消按鈕綁定取消登錄的邏輯
                                                  Button cancelBtn = new Button ( "取消");
                                                cancelBtn.oncliAction = page.CancelLogin;
                                                cancelBtn.Onclick ( null );
 
 
                                                  Hero dema = new Hero ();
                                                dema.HeroName =  "德瑪西亞" ;
                                                  //向左操作按鈕
                                                  Button leftBtn = new Button ( "a1");
                                                leftBtn.oncliAction = dema.LeftAction;
                                                leftBtn.Onclick ( null );
                                                  //s向左操作按鈕
                                                  Button rightBtn = new Button ( "d1");
                                                rightBtn.oncliAction = dema.RightAction;
 
                                                  //匿名方法1、無返回值的匿名方法:delegate(參數列表){ 方法體 }2、有返回值的匿名方法:delegate(int x,int y){return x+y}3、在將匿名方法賦值給委托的時候,末尾的 ; 不能忘
                                                  Addelegate delAdd = delegate (int x, int y) {
                                                                  return x + y;
                                                };
 
                                                  //2、lambda表達式:
                                                delAdd = ( int  x,int y) => {
                                                                  return x*y;
                                                };
                                                  Console.WriteLine (delAdd (4,5));
 
                                                  //Func:范型委托
                                                  Func<int ,int ,string, float> chu = (int x,int y,string name) => {
                                                                  Console.WriteLine (name);
                                                                  return x+y;
                                                };
 
                                                  Console.WriteLine (chu(3,5,"張三" ));
                                }
 
                                  //定義打印數組的委托
 
                                  public delegate int Addelegate( int x,int y);
 
                                  public delegate void Print(int[] arr);
                                  public delegate void VoidFunction( string _n);
 
                                  public static   void ChineseGreeting( string name){
                                                  Console.WriteLine ("早上好:" +name);
                                }
 
                                  public static void EngGreeting( string name){
                                                  Console.WriteLine ("good morning:" +name);
                                }
 
                                  public static int Add( int x,int y){
                                                  return x + y;
                                }
 
                                  public static int Mul( int x,int y){
                                                  return x * y;
                                }
                }
}
//================================================================
using  System;
 
namespace  Lesson13_2
{
 
                  public class Person{
                                  public string name;
 
                                  public void Congratulate(){
                                                  Console.WriteLine (this .name+" 祝賀新郎新娘百年好合~!" );
                                }
                }
 
                  public class Button{
                                  public string btnName;
                                  //事件的
                                  public delegate void OnclickHandler();
                                  public event OnclickHandler ClickEvent;
 
                                  public void AddClickListener(OnclickHandler clickCall){
                                                ClickEvent +=  new OnclickHandler (clickCall);
                                }
 
                                  public void Onclick(){
                                                  if (ClickEvent != null ) {
                                                                ClickEvent ();
                                                }
                                }
                }
 
                  public class CJBoy{
 
                                  public delegate void MarryHandle();
                                  //事件的發起者
                                  public event MarryHandle marryEvent;
                                
                                  public void SayLove(string qs){
                                                  Console.WriteLine ("黑負淚" );
                                }
 
                                  public void XYQ(){
                                                  Console.WriteLine ("送玫瑰" );
                                }
 
                                  public void Song(){
                                                  Console.WriteLine ("你笑的多甜蜜蜜蜜" );
                                }
 
                                  public bool Ask(string name){
                                                  Console.WriteLine ("你到底接不接受" );
                                                  return true ;
                                }
 
                                  public long PhoneNum(){
                                                  return 133010556;
                                }
 
                                  public void SendMessage(Action callback){
                                                  if (callback != null ) {
                                                                callback ();
                                                }
                                }
 
                                  //給事件添加一個監聽
                                  public void AddMarryListener(MarryHandle listener){
                                                marryEvent +=  new MarryHandle (listener);
                                }
 
                                  public void Marry(){
                                                  Console.WriteLine ("要結婚了" );
                                                  //事件觸發
                                                  if (marryEvent != null ) {
                                                                marryEvent ();
                                                }
                                }
                }
                  //delegate bool AskHandle();
                  //delegate bool AskHandle(string name);
 
 
 
                  class MainClass
                {
                                  public static void Main ( string[] args)
                                {
                                                  CJBoy boy = new CJBoy ();
 
                                                  //Func:用於創建有返回值類型的委托,
                                                  //注意,返回值一定義是最后那個參數
                                                  Func<string ,bool> laowang
                                                                =  new Func <string, bool> (boy.Ask);
                                                  bool result = laowang ("超級男孩" );
                                                  Console.WriteLine (result);
 
                                                  Func<long > laowang2 = new Func< long> (boy.PhoneNum);
                                                  Console.WriteLine (laowang2 ());
 
                                                  //Action: 用於創建沒有返回值類型的委托
                                                  Action<string > laowang3
                                                =  new Action <string> (boy.SayLove);
                                                laowang3 ( "流浪"  );
 
                                                  Action laowang4 = new Action (boy.Song);
                                                laowang4 ();
 
                                                boy.SendMessage ( delegate (){
                                                                  Console.WriteLine ("吃飯了嗎~!" );
                                                });
 
                                                  Person plaowang = new Person();
                                                plaowang.name =  "老王" ;
                                                  Person p2 = new Person();
                                                p2.name =  "老張" ;
                                                  Person p3 = new Person();
                                                p3.name =  "老李" ;
 
                                                boy.AddMarryListener (plaowang.Congratulate);
                                                boy.AddMarryListener (p2.Congratulate);
                                                boy.AddMarryListener (p3.Congratulate);
 
                                                  //結婚當天
                                                boy.Marry ();
 
                                                  //
                                                  Button loginBtn = new Button ();
                                                loginBtn.AddClickListener ( delegate (){
                                                                  Console.WriteLine ("登陸" );
                                                });
 
                                                  Button cancelBtn = new Button ();
                                                cancelBtn.AddClickListener ( delegate (){
                                                                  Console.WriteLine ("取消登陸" );
                                                });
 
                                                  Button skill1Btn = new Button ();
                                                skill1Btn.AddClickListener ( delegate (){
                                                                  Console.WriteLine ("大招" );
                                                });
 
                                                loginBtn.Onclick ();
 
                                                cancelBtn.Onclick ();
 
                                                skill1Btn.Onclick ();
                                }
                }
}
 
 

 

委托

作者: 1056923207@qq.com
委托的定義位置,可以放到類和方法同級,
也可以放到命名空間下和類同級。
委托的返回值:多播委托的返回值是最后一個方法的返回值;
匿名委托格式:   Pao p = delegate(){return 0 ;};
有參數有返回值的匿名委托:
一,用於創建有返回值類型的委托就用泛型委托;注意:返回值一定是尖括號最后的那個參數;
泛型委托:1. Func<bool> laowang =new Func<bool>(bool.Ask);
                    bool result = laowang();
 
                2.  Func<string ,bool> laowang =new Func<string,bool>(bool.Ask);
 
二,  Actiong:用於創建沒有返回值類型的委托:
               
               Action<string>   laowang3  = new Action<string>(boy.SayLove);

 

12作業

作者: 574096324@qq.com
《第十二講:C#語言編程》集合
 
課后題:
1. (*)用集合保存4個人的隨機投票,列出最終票數及各自的名字
 
2. (* *)在一個有限平面區域上(1000 * 1000)隨機生成有序的n個點(用結構體表示點),將其保存在集合中
  (1)輸出所有點的坐標信息
  (2)計算有序相鄰兩點距離之和(先排序,再求距離)
 
 
3. (* * *)隊列:仿照模擬經營類游戲中的情形,自定義一個窗口類,實例化一個窗口,一共有10位顧客,每位顧客接受服務的時間為2~3分鍾,求15分鍾后仍為接受服務的顧客名單。
 
using  System;
//非范型集合所在的命名空間
using  System.Collections;
//范型集合命名空間
using  System.Collections.Generic;
 
namespace  Lesson12
{
                  public class PrintTool{
                                  //專門輸出隊列的元素
                                  public void PrintStack(Stack a){
                                                  foreach (var item in a) {
                                                                  Console.Write (item+"  " );
                                                }
                                }
 
                                  public void PrintQueue(Queue< string> q){
                                                  foreach (var item in q) {
                                                                  Console.Write (item+"  " );
                                                }
                                                  Console.WriteLine ();
                                }
                }
 
                  class MainClass
                {
                                  public static void Main ( string[] args)
                                {
                                                  //集合:把一些能夠確定的不同的對象看成一個整體,
                                                  //                就說這個整體是由這些對象的全體構成的集合.
                                                  //元素:集合中每個對象叫做這個集合的元素.
                                                  PrintTool zhangsan = new PrintTool ();
                                                  Stack stack = new Stack ();
                                                  //Push:往集合里放一個東西
                                                stack.Push (1);
                                                stack.Push (5.4f);
                                                stack.Push ( "你好~!"  );
 
                                                  //可以用foreach訪問Stack集合里的元素
                                                zhangsan.PrintStack (stack);
 
                                                  //Pop:返回並移除集合頂部的對象
                                                  object propItem = stack.Pop ();
                                                  Console.WriteLine (propItem);
 
                                                  //可以用foreach訪問Stack集合里的元素
                                                zhangsan.PrintStack (stack);
                                                  object peekItem = stack.Peek ();
 
 
                                                  //賦值語句,條件語句
                                                  //stack.Clear ();
                                                  Queue<string > queue = new Queue< string> ();
                                                queue.Enqueue ( "張三"  );
                                                queue.Enqueue ( "李四"  );
                                                queue.Enqueue ( "王二"  );
                                                queue.Enqueue ( "麻子"  );
                                                queue.Enqueue ( "老王"  );
                                                zhangsan.PrintQueue (queue);
                                                  //返回隊列的第一個元素,並將這個元素從集合中刪除
                                                  string dequeueItem = queue.Dequeue ();
                                                  Console.WriteLine (dequeueItem);
                                                zhangsan.PrintQueue (queue);
                                                  //
                                                  //Dictionary:字典集合
                                                  Dictionary<int ,string> students =
                                                                  new Dictionary <int, string> ();
                                                  //往字典里存放值,key是唯一的,不能重復添加key
                                                students.Add (1,  "李逵" );
                                                students.Add (2,  "張飛" );
                                                students.Add (3,  "宋江" );
                                                students.Add (4,  "關羽" );
 
                                                  //用foreach迭代集合中的元素
                                                  foreach (var item in students) {
                                                                  Console.WriteLine (item.Value);
                                                }
                                                  //元素的訪問:變量名稱[key(鍵)]形式來訪問單個value元素
                                                  Console.WriteLine (students [1]);
                                                  //在直接通過索引方式去值的時候,
                                                  //要注意key在存在情況下才能去成功否則或報錯
                                                  if (students.ContainsKey (5)) {
                                                                  Console.WriteLine (students [5]);
                                                }  else {
                                                                  Console.WriteLine ("key不存在" );
                                                }
 
                                                  string value;
                                                  bool isGet = students.TryGetValue (5, out value);
                                                  Console.WriteLine (isGet + "  " + value);
 
                                                  //移除鍵以及鍵所對應的元素
                                                students.Remove (1);
                                                  //用foreach迭代集合中的元素
                                                  foreach (var item in students) {
                                                                  Console.WriteLine (item);
                                                }
                                                  //判斷是否存在指定的值
                                                  Console.WriteLine (students.ContainsValue ("張飛"));
 
                                                  //取得集合中的所有鍵
                                                  Dictionary<int ,string>. KeyCollection keys = students.Keys;
                                                  foreach (var item in keys) {
                                                                  Console.WriteLine (item);
                                                }
 
                                                  // “張三 ,2”
                                     // "李四 ,5"
                                                  // “wanger , 3”
//                                             Dictionary<string,int> voite = new Dictionary<string, int> ();
//                                             for (int i = 0; i < 10; i++) {
//                                                             string name = Console.ReadLine ();
//                                                             if (!voite.ContainsKey (name)) {
//                                                                             voite.Add (name, 1);
//                                                             } else {
//                                                                             voite [name] += 1;
//                                                             }
//                                             }
//
//                                             foreach (var item in voite) {
//                                                             Console.WriteLine (item);
//                                             }
 
                                                  //List<T> 動態數組
                                                  List<int > scores = new List< int> ();
                                                scores.Add (1);
                                                scores.Add (2);
                                                scores.Add (3);
                                                scores.Add (4);
                                                scores.Add (5);
 
                                                  //Insert,從指定的索引位置插入元素
                                                scores.Insert (3, 6);
                                
                                                  //Remove:刪除指定元素
                                                scores.Remove (6);
 
                                                  //RemoveAt:刪除指定索引位置的元素
 
                                                  //Reverse:
                                                scores.Reverse ();
                                                  //
                                                scores.Sort ();
                                                  foreach (var item in scores) {
                                                                  Console.WriteLine (item);
                                                }
 
 
                                }
                }
}

 

ArryList和List<T>

作者: 1056923207@qq.com
《第十二講:C#語言編程》集合

課后題:
1. (*)用集合保存4個人的隨機投票,列出最終票數及各自的名字

2. (* *)在一個有限平面區域上(1000 * 1000)隨機生成有序的n個點(用結構體表示點),將其保存在集合中
  (1)輸出所有點的坐標信息
  (2)計算有序相鄰兩點距離之和(先排序,再求距離)

 
3. (* * *)隊列:仿照模擬經營類游戲中的情形,自定義一個窗口類,實例化一個窗口,一共有10位顧客,每位顧客接 受服務的時間為2~3分鍾,求15分鍾后仍未接受服務的顧客名單。
 
 
第一題:
//實例化一個字典對象(代碼放在主函數里面)
             Dictionary<string , int > dic = new Dictionary< string, int>();
           
             for ( int i = 0; i < 4; i++)
            {
                 string name = Console.ReadLine();
                 if (dic.ContainsKey(name))
                {
                    dic[name] += 1;
                }
                 else
                {
                    dic.Add(name, 1);
                }
            }
             foreach ( var item in dic)
            {
                 Console.WriteLine(item);
            }
 
第二題:
(1)
namespace  集合
{
     struct Point
    {
       public   float x;
        public  float y;
    }
  
 
     class Program
    {
         static void Main( string[] args)
        {
             List< Point> li = new List< Point>();
             Random ran = new Random();
             Point p = new Point();
             for ( int i = 0; i < 5; i++)
            {
                p.x = ran.Next(0, 1000);
                p.y = ran.Next(0, 1000);
                li.Add(p);
            }
 
             foreach ( var item in li)
            {
                 Console.WriteLine( "x坐標為{0},y坐標為{1}" ,item.x,item.y);
 
            }
           
        }
    }
}
第二題
namespace  集合
{
    public  struct Point
    {
         public float x;
         public float y;
    }
 
 
     public static class Tool
    {
         public  static double Dis( Point p1, Point p2)
        {
             double m = (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
             double z = Math.Sqrt(m);
             return z;
        }
 
 
    }
 
  
  
 
     class Program
    {
         static void Main( string[] args)
        {
             List< Point> li = new List< Point>();
             Random ran = new Random();
             Point p = new Point();
             for ( int i = 0; i < 5; i++)
            {
                p.x = ran.Next(0, 1000);
                p.y = ran.Next(0, 1000);
                li.Add(p);
            }
             for ( int i = 0; i < 4; i++)
            {
                 for ( int j = 0; j < 4-i; j++)
                {
                     if (li[j].x>li[j+1].x)
                    {
                         Point item = li[j];
                        li[j] = li[j + 1];
                        li[j + 1] = item;
                       
 
                    }
                }
            }
             double totaldistance = 0;
             for ( int i = 4; i > 0; i--)
            {
                totaldistance +=  Tool.Dis(li[i], li[i -1]);
            }
             Console.WriteLine(totaldistance);
 
             foreach ( var item in li)
            {
               
                 Console.WriteLine( "x坐標為{0},y坐標為{1}" ,item.x,item.y);
 
            }
           
        }
    }
}
 
第三題:
  class  Program
    {
         static void Main( string[] args)
        {
             Random ran = new Random();
             Queue< int> t = new Queue< int>();
             int sum = 0;
             int z;
             for ( int i = 0; i < 9; i++)
            {
                 int n = ran.Next(2, 4);
                sum += n;
                 if (sum <= 15) 
                {
                    t.Enqueue(n);
                }
                 else
                {
                    z = 9 - i;
                     Console.WriteLine( "還有{0}位客人沒有接受服務" , z);
                     break;
                }
 
            }
          
           
        }
    }

 

冒泡排序,選擇排序

作者: 574096324@qq.com
冒泡排序
            int[] a = { 48, 39, 65, 97, 76, 13 };
             for (int i = 0; i < a.Length-1; i++)
            {
                 for (int j = 0; j < a.Length-1-i; j++)
                {
                     if(a[j]>a[j+1])
                    {
                         int temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
             for (int i = 0; i < a.Length; i++)
            {
                 Console.WriteLine(a[i]);
            }
////選擇排序
             //int[] a = { 48, 39, 65, 97, 76, 13 };
             ////每一趟都會找出一個最小值,第一堂吧最小值與第一個元素交換,第二趟找出除第一個元素之外的元素里面的最小值
             ////並與第二個元素進行交換,以此類推
             ////聲明兩個變量一個存放最小值,一個存放最小值對應的下標
             //int min, minIndex;
             ////外層循環控制趟數
             //for (int i = 0; i < a.Length-1; i++)
             //{
             //    //當i等於0,把a[0]當成最小值,如果i=1,則把a[1]當成最小值
             //    min = a[i];
             //    minIndex = i;
             //    for (int j =i+1 ; j <a.Length ; j++)
             //    {
             //        if (min>a[j])
             //        {
             //            min = a[j];
             //            minIndex = j;
             //        }
             //    }
             //    //把a[i]的值與最小值所在下標的元素進行交換
             //    a[minIndex] = a[i];
             //    //把最小值min賦值給a[i],完成兩個元素值得交換
             //    a[i] = min;
             //}
             //for (int i = 0; i < a.Length; i++)
             //{
             //    Console.WriteLine(a[i]);
             //}
 
int[,] a = new int[4, 3];
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    a[i, j] = int.Parse(Console.ReadLine());
                }

            }
            //打印數組
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    Console.Write(a[i, j] + " ");
                }
                Console.WriteLine();
            }
            for (int i = 0; i < a.GetLength(1); i++)
            {
                Console.Write(a[0, i] + " ");
            }
            int sum = 0;
            for (int i = 0; i < a.GetLength(1); i++)
            {
                sum += a[1, i];
            }
            Console.WriteLine("sum=" + sum);
 
 
 
類名方法名大寫

 

unity引擎組件

作者: 1056923207@qq.com
兩種打印的方式:1.print,繼承於MonoBehaviour類;只有在繼承MoNoBehaviour類的時候才能用
                         
 
                          2. debug.log;  debug類中還有兩個只能在Sence模塊看到的測試划線1.Drawline(Vector3 start,Vector3 end);
                                                                                                                                2.DrawRay(Vector3 start,Vector3 dir);
 
GameObect類的屬性:tag,name FindGameObjectsWithTag(string tag)  T GetComponent<T>()  SetActive(bool value)  FindWithTag(string tag)

 

集合

作者: 1056923207@qq.com
字典元素的訪問:可以用foreach將字典鍵值對的完整信息打印出來,也可以通過索引僅僅輸出鍵的值、
                         在直接通過索引取值的時候要注意:key值要在存在的情況下才能取成功;

 

抽象方法

作者: 1056923207@qq.com
抽象方法:在父類中定義不能實現
              ;只能出現在抽象類中 
             :方法返回值前面要加abstract
              ;子類實現抽象方法的時候需要加abstract;

 

基本數據類型

作者: 574096324@qq.com
1.int類型 4字節  32位整型   uint 無符號整型 unsigned
2. 單精度浮點數(float)4字節    后面加f,例如:23.5f,23f
3.雙精度浮點數(double)8字節 后面加d 也可不加,例如:23.5,14.7d
4.128位高精度浮點數(decima) 16字節 后綴m ,例如:15.67m,它的取值范圍上面兩種浮點類型小,但精確度最高。
5.字符類型(char)2字節,用單引號引起來,例如‘0’
6.字符串(string)由0個,1個或者2個以上的字符組成並用雙引號引起來,“0”,“1”,“lisi”
7.布爾類型(bool),取值只能為true或false
 
數組,枚舉,結構體

 

枚舉,結構體

作者: 1056923207@qq.com
枚舉類型的變量只有賦值之后才能使用,並且所賦的值必須是有效的:不同的枚舉可以有相同的值,不會沖突,比如week.day和month.day;
 
結構體:使用結構體的成員時的格式:結構體類型變量.成員名        Person p ;                 p.name=nignyognbin;
           :結構體的成員都不允許直接初始化(不能直接賦值):

 

泛型

作者: 1056923207@qq.com
泛型方法:public void 方法名字  <類型>(){}
泛型類:Test<int> a = new Test<int> ();
泛型參數的約束:public class Test<T>Where T:Struct {}         只能是值類型的
                       :public class Test<T>Where T:Class {}         只能是引用類型的
 

 

接口與泛型

作者: 574096324@qq.com
接口與泛型
1.接口的定義:訪問修飾符interface接口名{成員}
2.接口是一個抽象的該年,目的在於子類實現它
3.接口通常用來定義不同類之間的統一的標准
4.接口的成員:包括方法、屬性、事件、索引、不能有字段
5.接口成員不能加修飾符,默認為public並且要求實現類(子類)去實現接口里的所有接口成員
6.接口和抽象類一樣,是抽象的概念,所以不能創建對象(不能new)
7.如果一個類實現多個接口,接口之間用逗號","
8如果一個類同時繼承一個父類,又實現一個或多個接口,那么父類放在最前面

 

委托事件

作者: 574096324@qq.com
 
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
 
namespace  Weituoshijian
{
     //英雄類
     class Hero
    {
         //屬性……
         //private int hp;
 
         public delegate void AttackHandler();
         //攻擊方法1
         public void Attack(AttackHandler method)
        {
            method();
        }
 
         //攻擊方法2
         public void Attack(int index)
        {
             //這樣寫不靈活,擴展型太差
             if (index==0)
            {
                 //ToDo……
                 //SF.Skill_Q();     回調
                Skill_Q();
            }
             else if (index==1)
            {
                Skill_W();
            }
             else
            {
                 Console.WriteLine("普通攻擊" );
            }
        }
         //一堆技能
         public void Skill_Q()
        {
             Console.WriteLine("我正在使用Q技能" );
        }
         public void Skill_W()
        {
             Console.WriteLine("我正在使用W技能" );
        }
    }
     //學生,玩游戲,讓班長盯梢,老師來了告訴我一聲
     class Student
    {
         //接受消息
         public void ReceiveMsg(string msg)
        {
             Console.WriteLine("我接收到消息:" + msg);
        }
         //讓班長盯梢
         public void WatchDog(Master master)
        {
             //老師來了回調那個方法
            master.action += ReceiveMsg;
             //告訴你啥?
            master.msg =  "老師來了" ;
          
        }
 
    }
 
     class Master
    {
         //可以接活:事件綁定
         //事件就是委托的封裝,外面綁定,不能調用
         public event Action< string> action;
         //暗號
         public string msg;
 
         //掙錢
         public void EarnMoney()
        {
            action(msg);
        }
         //盯梢
         public void WatchTeacher()
        {
             while (true )
            {
                 int num = int .Parse(Console.ReadLine());
                 if (num == 10)
                {
                    EarnMoney();
                     break;
                }
            }
        }
    }
 
     class Program
    {
         static void Main(string[] args)
        {
             ////創建一個對象
             //Hero SF = new Hero();
             ////調用攻擊方法
             //SF.Attack(SF.Skill_Q);
             Student s = new Student();
             Master m = new Master();
            s.WatchDog(m);
            m.WatchTeacher();
 
             Console.ReadKey();
        }
    }
}

 

12集合

作者: 574096324@qq.com
前面的類 
class MyList
    {
 
         private int [] arr = new int[10];
 
         public int this[int index]
        {
             get
            {
                 if (index >= arr.Length)
                {
                     return 0;
                }
                 else if (index < 0)
                {
                     return 0;
                }
                 else {
                     return arr[index];
                }
            }
             set
            {
                 if (index >= 0 && index < arr.Length)
                {
                    arr[index] =  value;
                }
            }
        }
    }
 
     public static class PrintTool
    {
         public static void PrintStack( Stack stack)
        {
             foreach (object item in stack)
            {
                 Console.WriteLine(item);
            }
             Console.WriteLine();
             Console.WriteLine("-----------" );
        }
 
         public static void PrintQueue( Queue queue)
        {
             foreach (var item in queue)
            {
                 Console.WriteLine(item);
            }
             Console.WriteLine("\n-----------" );
        }
    }
 
 
主函數里面的
//Stack 的用法:
             Stack stack = new Stack();
             //Push方法:往集合里添加一個元素,並且把這個元素放到頂部
            stack.Push(1);
            stack.Push(  "lanou");
             //Person p = new Person ();
             //stack.Push (p);
             PrintTool.PrintStack(stack);
 
             //Pop方法:移除並返回集合頂部的對象
             object popItem = stack.Pop();
             Console.WriteLine("popItem:" + popItem);
             PrintTool.PrintStack(stack);
 
             //Peek方法:返回集合中頂部的對象
             object peekItem = stack.Peek();
             Console.WriteLine(peekItem);
             PrintTool.PrintStack(stack);
 
             //Contains:判斷集合中是否存在這個元素
             bool cItem = stack.Contains("lanou" );
             Console.WriteLine(cItem);
 
             //Clear:刪除集合中的所有元素
            stack.Clear();
             PrintTool.PrintStack(stack);
 
             //Count:返回集合中當前元素個數
             int count = stack.Count;
             Console.WriteLine(count);
 
            stack.Push(1);
 
             //Colne:
             int[] a = { 1, 2, 3, 4 };
             int[] b;
            b = (  int[])a.Clone();
            b[0] = 2;
             foreach (var item in b)
            {
                 Console.WriteLine(item);
            }
             Console.WriteLine(a.Equals(b));
 
             //Queue:隊列, 先進先出
             Queue queue = new Queue();
             //Enqueue: 將一個元素放入集合的尾部
            queue.Enqueue(1);
            queue.Enqueue(  "lanou");
            queue.Enqueue(1.5);
            queue.Enqueue(5.0f);
             PrintTool.PrintQueue(queue);
 
             //Dequeue: 將集合首個元素刪除,並返回
             object deItem = queue.Dequeue();
             Console.WriteLine(deItem);
             PrintTool.PrintQueue(queue);
 
             //Add:往集合中添加指定的鍵、值元素
             Dictionary<int , string> dic = new Dictionary <int, string>();
            dic.Add(101,  "張三");
            dic.Add(102,  "李四");
            dic.Add(103,  "李四");
 
             foreach (var item in dic)
            {
                 Console.WriteLine("key:" + item.Key + "   value:" + item.Value);
            }
             Console.WriteLine("-------------" );
 
             //TryGetValue:嘗試通過鍵去獲得值,若成功則返回true,並且將鍵相應的值
             //通過out參數返回,否則返回false,out參數返回“”字符串
             string tryItem;
             bool tryResult = dic.TryGetValue(105, out tryItem);
             Console.WriteLine("tryItem:" + tryItem + "   tryResult:" + tryResult);
 
             foreach (var item in dic)
            {
                 Console.WriteLine("key:" + item.Key + "   value:" + item.Value);
            }
             Console.WriteLine("-------------" );
             //Clear:
             //dic.Clear ();
             foreach (var item in dic)
            {
                 Console.WriteLine("key:" + item.Key + "   value:" + item.Value);
            }
             Console.WriteLine("-------------" );
 
             //Remove:刪集合中指定鍵值
            dic.Remove(102);
             foreach (var item in dic)
            {
                 Console.WriteLine(item);
            }
 
             //字典取值:可以通過[key]的方式來取的對應的值
             string value = dic[101];
             Console.WriteLine("101:" + value);
 
             //ContainsKey:判斷集合中是否存在某個鍵
             bool isFindKey = dic.ContainsKey(105);
             Console.WriteLine(isFindKey);
             //ContainsValue: 判斷集合中是否存在某個值
             bool isFindValue = dic.ContainsValue("老王" );
             Console.WriteLine(isFindValue);
 
             //遍歷集合中的所有鍵
             //1. 把keys放到變量中
             /*Dictionary<int ,string>.KeyCollection keys = dic.Keys;
                                                foreach (var item in keys) {
                                                                
                                                }*/
 
             foreach (var item in dic.Keys)
            {
                 Console.WriteLine(item);
            }
 
             //遍歷集合中的所有值
             foreach (var item in dic.Values)
            {
                 Console.WriteLine(item);
            }
 
             // 用戶輸入10個姓名,可以重復輸入同一個姓名,
             //輸出每個姓名,並輸出每個姓名輸入的多少次。
             /*Dictionary<string ,int> student = new Dictionary<string, int> ();
                                
                                                for (int i = 0; i < 10; i++) {
                                                                //輸入一個學生的名字
                                                                string name = Console.ReadLine ();
                                                                //如果該學生已經被添加到集合中,那么將他的票數加1
                                                                if (student.ContainsKey (name)) {
                                                                                student [name] += 1;
                                                                } else {//否則,加入這個學生,並且初始票數設置為1
                                                                                student.Add (name , 1);
                                                                }
                                                }
 
                                                foreach (var item in student) {
                                                                Console.WriteLine (item.Key+":"+item.Value);
                                                }*/
 
 
             //--------
             ArrayList arrayList = new ArrayList();
            arrayList.Add(1);
            arrayList.Add(2);
            arrayList.Add(  'A');
            arrayList.Add(  "sss");
 
             foreach (var item in arrayList)
            {
                 Console.WriteLine(item);
            }
 
             //AddRange:可以將一個繼承了ICollection接口的集合里面的
             //元素挨個添加進來
             //把一個字典加入的arraylist中
            arrayList.AddRange(dic);
             //
            arrayList.AddRange(queue);
 
             foreach (var item in arrayList)
            {
                 Console.WriteLine(item);
            }
             //Contains:
            arrayList.Contains(  'A');
 
             //可以將集合中的元素通過此方法,拷貝到一個足夠長的數組中
             object[] arr = new object[arrayList.Count];
            arrayList.CopyTo(arr);
 
             Console.WriteLine("CopyTo---------------" );
             foreach (var item in arr)
            {
                 Console.WriteLine(item);
            }
 
             //取值方式和一維數組一樣
             Console.WriteLine(arrayList[0]);
 
             MyList mylist = new MyList();
            mylist[0] = 12;
             Console.WriteLine(mylist[0]);
 
             Console.ReadKey();

 

11接口,泛型

作者: 574096324@qq.com
1. 接口:
定義IBattle接口、聲明攻擊Attack(),移動Move(), 跳躍Jump()等方法;
   定義IRest接口、聲明SitDown(),Sleep()等方法;
   定義Soldier(戰士)、Master(法師)、Assassin(刺客)、Archer(弓箭手)等類,繼承上述接口,並實現內部方法。

2. 定義MyList類,該類模擬一個動態數組,可以用來存放數據(以int類型為例)。實現如下功能:
1)定義屬性Count,表示當前動態數組存放的int型元素個數;
2)定義方法Clear(),可以清空所有的元素;
3)定義方法Add(),可以實現添加元素的功能;
4)定義方法Insert(int value, int index),可以實現在某個位置插入元素的功能;
5)定義方法Reverse(),可以實現元素的反轉。
6)定義方法Contains(),可以查找元素是否存在。 

3. 老板招募小秘
(1)當秘書必須要實現的協議用接口IScretary表示。
要想當秘書,必須能夠實現如下方法:
端茶倒水
開車
捶背
提包等
(2)有兩類人前來應聘秘書:
男人類 Man
女人類 Woman
機器人類 Robot
請讓以上三個類繼承秘書協議,並根據每個類的特點實現協議中的方法
(3)在Main方法中分別創建男秘對象和女秘對象,並自行設計模擬情景。
如:有一天老板招了一個男秘,讓他干這干那,后來不滿意,又招了一個女秘...
   再后來科技突飛猛進,老板雇佣了一個不知疲倦聰明又從來不抱怨的機器秘書
 
2.
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  System.Threading.Tasks;
/*2. 定義MyList類,該類模擬一個動態數組,可以用來存放數據(以int類型為例)。實現如下功能:
1)定義屬性Count,表示當前動態數組存放的int型元素個數;
2)定義方法Clear(),可以清空所有的元素;
3)定義方法Add(),可以實現添加元素的功能;
4)定義方法Insert(int value, int index),可以實現在某個位置插入元素的功能;
5)定義方法Reverse(),可以實現元素的反轉。
6)定義方法Contains(),可以查找元素是否存在。 */
namespace  h2
{
     interface IInterface
    {
 
    }
     class MyList< T>
    {
         //該字段用來記錄數組里面所放元素的個數
         private int length;
         //用來記錄數組的容量,即最多可放元素的個數
         private int capacity;
         //數組用來存取數據
         private T [] a;
         //在默認構造方法里面給字段賦初值
         public MyList()
        {
             //數組元素的個數初始值為0
            length = 0;
             //數組容量初始值為8
            capacity = 8;
             //給數組開辟空間
            a =  new T [capacity];
        }
         /// <summary>
         /// 屬性,得到數組的元素的個數
         /// </summary>
         public int Count
        {
             get
            {
                 return length;
            }
        }
         public void Add(T x)
        {
             //先判斷數組的容量是否可以再返給數據
             if (length>=capacity)
            {
                 //如果不能再放入數據,擴充數組容量
 
            }
             //把要加的數據方法放到數組里面
            a[length] = x;
             //數組元素的個數要加1
            length++;
        }
         /// <summary>
         /// 擴充數組容量的方法
         /// </summary>
         private void EnlargeCapacity()
        {
             //把容量值增加
            capacity += 8;
             //根據增加后的容量創建新數組
             T[] temp = new T[capacity];
             //把a數組里面的元素復制到新數組里面
             for (int i = 0; i < length; i++)
            {
                temp[i] = a[i];
            }
             //把a指向新數組
           a =temp;
        }
         /// <summary>
         /// 清空數組
         /// </summary>
         public void Clear()
        {
             //數組元素為0
            length = 0;
             //數組容量為8
            capacity = 8;
             //創建一個新的數組
            a =  new T [capacity];
        }
         public bool Contains(int x)
        {
             for (int i = 0; i < length; i++)
            {
                 if (x.Equals(a[i]))
                {
                     return true ;
                }
            }
             return false ;
        }
         //數組的反轉
         public void Reverse()
        {
             for (int i = 0; i < length/2; i++)
            {
                 T temp = a[i];
                a[i] = a[length - 1 - i];
                a[length - 1 - i] = temp;
            }
        }
         /// <summary>
         /// 插入
         /// </summary>
         /// <param name=" index"></param>
         /// <param name=" num"></param>
         public void Insert(int index, T num)
        {
             if (length>=capacity)
            {
                EnlargeCapacity();
            }
             //如果插入的位置在數組之外
             if (index<0)
            {
                 Console.WriteLine("index不能小於0" );
                 return;
            }
             //如果插入的位置剛好在所有元素的最后面
            else if (index ==length)
            {
                a[index]= num;
                length += 1;
            }
             else if (index >= length + 1)
            {
               
            }
             else
            {
                 //把數組里面index之后的所有元素往后面移動一位
                 for (int i = length-1; i >=index; i--)
                {
                    a[i + 1] = a[i];
 
                }
                a[index] = num;
                length += 1;
            }
        }
         /// <summary>
         /// 打印數組
         /// </summary>
         public void PrintArray()
        {
             //使用for循環把存到數組a里面的元素打印出來
             for (int i = 0; i < length; i++)
            {
                 Console.WriteLine(a[i]);
            }
        }
    }
     class Program
    {
         static void Main(string[] args)
        {
             MyList<int > list = new MyList< int>();
            list.Add(5);
            list.Add(6);
            list.Add(7);
            list.PrintArray();
            list.Insert(1, 9);
            list.PrintArray();
 
             Console.ReadKey();
        }
    }
}
  

 

10作業

作者: 574096324@qq.com
課后題:
第一題 定義一個打印機類(printer)。需求:
1. 采用單例模式
2. 定義成員變量:打印機IP地址(靜態變量),打印數量,紙張類型(數值為枚舉類型)
3. 定義方法:根據打印機IP地址連接打印機;打印功能;打印失敗提醒功能

第二題 模擬打僵屍。需求:
  定義僵屍類:
公共成員變量:類型、總血量、每次失血量
方法:初始化方法(設置僵屍種類,總血量)、被打擊失血(抽象方法)、死亡(抽象方法)

 定義普通僵屍類繼承於僵屍類

定義有防具(路障)僵屍類繼承於僵屍類:
特有成員變量:防具類型
特有方法:防具被打爛

定義鐵桶僵屍類繼承於有防具僵屍:
特有成員變量:弱點
特有方法:防具被磁鐵吸走

1、創建普通僵屍對象,設置總血量50,每次失血量為 3
2、創建路障僵屍對象,設置總血量80,有路障時,每次失血量為 2
3、創建鐵桶僵屍對象,設置總血量120,有鐵桶時,每次失血量為 1
4、選作:
在Main方法里面里用循環語句模擬攻擊:
三個僵屍對象同時被攻擊:
(1)、普通僵屍被打擊時:每次失血3.
(2)、路障僵屍被打擊時:有路障時,每次失血2,血量剩余一半時,防具被打攔,之后每次失血3.
(3)、鐵桶僵屍被打擊時:有鐵桶時,每次失血1,血量剩余1/3時,鐵桶被打攔,之后每次失血3.
循環攻擊過程中:每個僵屍被攻擊時,輸出本次丟失血量,剩余血量。失去道具時,輸出丟失的道具。僵屍死亡時,輸出已死亡。
最后一個僵屍死亡時,攻擊停止,循環結束。輸出總攻擊次數。
/*------------------------------------------------------*/
打僵屍
using  System;
 
namespace  Zombie
{
 
     //創建僵屍的基類,把共有的字段和方法寫在基類里面
     //子類就可以直接調用或者重寫方法
     class Zombie
    {
         //血量
         public int HP { get; set; }
         //失血量
         public int LP { get; set; }
         //虛方法,由子類重寫,如果子類不重寫,則調用父類
         //里面的方法,如普通僵屍就是調用的父類里面的方法
         public virtual void BeAttacked()
        {
             //打印血量的值
             Console.WriteLine("僵屍的血量hp:" + HP);
             //血量減去失血量
            HP -= LP;
 
             //如果血量小於或者等於0
             if (HP <= 0)
            {
                HP = 0;
                 //調用死亡的方法
                Die();
            }
        }
         //虛方法,當僵屍的血量小於或者等於0時調用該方法
         public virtual void Die()
        {
             Console.WriteLine("僵屍死亡" );
        }
    }
     //普通僵屍繼承僵屍的基類,所有的方法都是調用的基類的
     class Normal : Zombie
    {
         //給普通僵屍字段初始化
         public Normal(int hp, int lp)
            :  base()
        {
             this.HP = hp;
             this.LP = lp;
        }
    }
     //定義路障僵屍類繼承於僵屍類
     class RoadBlock : Zombie
    {
         public RoadBlock()
        {
 
        }
         //初始化賦值,用帶參數的構造方法
         public RoadBlock(int hp, int lp, bool haveRoad)
            :  base()
        {
             this.HP = hp;
             this.LP = lp;
             this.haveRoadBlock = haveRoad;
        }
         //該字段是受保護的,只能在子類和父類內部使用
         //字段的含義是是否有路障,初始值為true
         protected bool haveRoadBlock;
         //重寫被攻擊的方法
         public override void BeAttacked()
        {
             Console.WriteLine("路障僵屍血量:" + this.HP);
             //血量減去失血量
             this.HP -= this .LP;
 
             //當血量小於或者等於總血量的一半時
             if (this .HP <= 40)
            {
                 //路障丟失,調用路障丟失的方法
                DefenceLost();
            }
             //如果沒有路障,則把失血量改為3
             if (haveRoadBlock == false )
            {
                 this.LP = 3;
            }
             //如果血量小於0,調用死亡的方法
             if (this .HP <= 0)
            {
                 this.HP = 0;
                Die();
 
            }
        }
         //虛方法,子類進行重寫,丟失路障的方法
         public virtual void DefenceLost()
        {
            haveRoadBlock =  false;
             Console.WriteLine("丟失路障" );
        }
         //重寫了父類里面的虛方法
         public override void Die()
        {
             Console.WriteLine("路障僵屍死亡" );
        }
    }
     //鐵桶僵屍繼承路障僵屍
     class Bucket : RoadBlock
    {
         //初始化
         public Bucket(int hp, int lp, bool haveBucket)
            :  base()
        {
             this.HP = hp;
             this.LP = lp;
             this.haveRoadBlock = haveBucket;
        }
         //重寫了受到攻擊的方法
         public override void BeAttacked()
        {
             Console.WriteLine("鐵桶僵屍的血量:" + this.HP);
             this.HP -= this .LP;
 
             if (this .HP <= 40)
            {
                DefenceLost();
            }
             if (haveRoadBlock == false )
            {
                 this.LP = 3;
            }
             if (this .HP <= 0)
            {
                 this.HP = 0;
                Die();
            }
        }
 
         public override void Die()
        {
             Console.WriteLine("鐵桶僵屍死亡" );
        }
 
    }
 
     class MainClass
    {
         public static void Main( string[] args)
        {
             Normal normal = new Normal(50, 3);
             RoadBlock road = new RoadBlock(80, 2, true);
             Bucket bucket = new Bucket(120, 1, true);
             int num = 1;
             do
            {
                 Console.WriteLine("第{0}回合" , num);
                num++;
                normal.BeAttacked();
                road.BeAttacked();
                bucket.BeAttacked();
                 //如果三種僵屍的血量都小於0,跳出循環
                 if (normal.HP <= 0 && road.HP <= 0 && bucket.HP <= 0)
                {
                     break;
                }
            }  while (true );
             Console.ReadKey();
        }
    }
}

 

09作業

作者: 574096324@qq.com
1.(**)定義一個矩形類(Rectangle),
成員變量:width,height,
XYPoint類型的point(原始點),
XYPoint類型的center(中心點)。
方法:封裝變量為屬性,構造方法初始化成員變量,
計算周長、計算面積(ref/out參數修飾)

2. (**) 定義玩家類(Player),並創建玩家對象
(1) 包含屬性:出生日期、星座
(2) 構造方法:根據玩家出生日期設置星座
(提示:星座設置可參考第二講作業)

3. (**) 定義如下類

裝備類:
特征:名稱

武器類 繼承 裝備類:
    特征:等級、攻擊力
    行為:攻擊

法杖類 繼承 武器類:
行為:遠程魔法攻擊(實現方法替換)

弓箭類 繼承 武器類:
行為:遠程物理攻擊(實現方法替換)

長劍類 繼承 武器類:
獨有特征:防御力
行為:進展物理攻擊(實現方法替換)

防具類 繼承 裝備類:
特征:防御力、耐久度
行為:破損

4. (***)
 
按如下繼承關系定義類
要求:
1. 每個類包含2個以上私有成員變量、保護成員變量
2. 每個類所有字段都封裝成屬性
3. 每個類至少有一個屬性為只讀和只寫
4. 每個類有兩個以上初始化方法
5. 動物類有一個移動的方法(move),子類重寫(重新實現)該方法
6. 為哺乳類添加特有的虛方法(sayHi),子類重寫該方法
7. 其它方法可以盡情發揮
8. 在Main方法中創建各個類的對象,調用類的方法


5.(***) 定義英雄類和Boss類,創建3個英雄對象,分別拿不同的武器(用第三題的類創建),對敵人循環回合制攻擊,輸出戰斗過程。

英雄類:
特征:HP、MP、類型(枚舉類型:弓箭手、法師、騎士)、武器(用第一題定義的類)
行為:攻擊、防御

Boss類:
特征:HP、攻擊力、防御力
行為:攻擊


(提示:以上各個類及其特征和行為可以自行設計豐富,為項目期做儲備)

 

09面向對象

作者: 574096324@qq.com
構造方法
            構造方法,是與類名相同,並且無返回值,不加void
            構造方法的主要作用是創建對象並給對象賦初值
            不帶有參數的構造方法稱為默認構造
            構造方法可以帶有參數進行重載, 如果要給對象賦具體的初始值時
            可以在類里面寫出帶有參數的構造方法並調用
            如果在類里面沒有構造方法,當我們創建對象時,系統會自動生成一個默認構造供使用
            如果類里面有帶有參數的構造方法,調用默認構造時,必須顯示的把默認構造寫出來
 
 面向對象三大特性:封裝、繼承、多態
             封裝
            我們在創建對象時,不希望外部人為的來破壞對象所包含的字段的值,此時就需要把數據封裝起來
            具體的做法是:把成員字段用private字段修飾,這樣外部就無法拿到字段並修改所存儲的數據
            同時把私有的字段改成屬性,通過屬性來修改字段的值,創建對象並初始化對象時
            可以用帶有參數的構造方法給字段賦初始值,把字段寫成私有后,雖然在外部不能使用,但是在類的內部可以使用、
            即類內部的方法可以調用類里面的私有字段
            繼承
            當一個子類繼承父類,會把父類里面的成員繼承過來,
            父類里面的成員如果用public修飾,稱為共有繼承,用private修飾稱為私有繼承
            公有繼承的成員在任何地方都能使用
            私有繼承過來的成員只能在分類內部使用,在類的額外面不能使用
            protected繼承過來的成員只能在父類和子類里面使用,類的外面不能使用
//里氏轉換
             SmallDog small = new SmallDog();
             BigDog big = new BigDog();
            stu.WalkDog(big);
            stu.WalkDog(small);
             //在處理數據時,為了使所處理的數據,類型達到統一,
             //此時會把數據的類型統一寫成父類的類型,這樣就可以吧子類的對象直接賦值給父類
             //里氏轉換的第一個原則:把子類對象賦值給父類,但是調用類里面的成員時只能調用父類里面的子類里面的調用不到
             Dog dog = small;
             //里氏轉換的第二個原則;把父類的對象轉成子類,as
             BigDog s =dog as BigDog;
             if (s!=null )
            {
                s.BigDogBark();
            }
//把值類型轉換成引用類型的過程稱為裝箱
             object obj = a;
             Console.WriteLine(obj);
             //把引用類型轉換成值類型稱為拆箱
             int c=(int )obj;
多態
virtual override

 

08作業

作者: 574096324@qq.com
1. (**)輸入一個字符串,”beijinglanoukeji,lanoukeji is great, I love lanou and unity”,,完成如下要求:
(1)判斷字符串是否存在lanou,如果存在lanou則輸出第一個坐標; 
(2)將字符串中出現的所有lanou替換為lanou3g,並輸出最后一個lanou3g的坐標;
(3)講字符串改為大寫輸出出來;
(4)判斷字符串是否存在“,”,若存在則按字符串“,”分組,輸出字符串數組長度,輸出所有字符串。

2. (**)定義一個計算器(Computer)類:
包含方法:
(1) 返回兩個數的最大值
(2) 返回三個數的最大值
(3) 返回兩個數的最小值
(4) 返回三個數的最小值
(5) 返回兩個數的和
(6) 返回三個數的和
…… (可以自由擴展和完善這個類) ……

3.(***)有一個GET網絡請求中,網絡連接(url字符串)通常是如下形式:
http://msdn.microsoft.com/zh-CN/?query=string
其中?后面表示參數。上面的例子中,參數名為query的參數值為string
(1) 判斷一個字符串是否是合法的url字符串(以http://或https://開頭)
(2) 判斷網絡連接中是否包含參數(提示:通過是否有?判斷)
 
4.(****)樓梯有N(小於50的整數)階,上樓可以一步上一價,也可以一(3) 封裝一個方法,輸入url字符串,返回其參數名和參數值
次上二階。編一個程序,計算共有多少種不同的走法。(遞歸實現)


5.(**)編寫一個GameObject類,寫一個GetComponent()方法,要求實現兩個以上的重載方法,一個參數為string類型,一個參數為自定義枚舉類型。方法返回值為string類型,返回一句話,說明調用的是什么方法,參數值是什么。

 

07作業

作者: 574096324@qq.com
1. (**)定義分數(Fraction)類:
1)、成員變量
   私有字段以及可讀可寫屬性:分子、分母
 
2)、成員方法:
 
(1)打印分數信息(例如: 1 / 3)
(2)約分
(3)創建一個方法交換分子和分母的值
(4)創建一個方法能同時得到加、減、乘、除、求余運算;
 
2. (**) 定義一個Car類,用成員變量表示品牌,當前速度,最大速度和方向(假設有東南西北四個方向),為其添加顯示速度、顯示方向、加速、減速以及轉盤(可以向左轉向右轉)方法
在Main方法中創建Car類對象,並調用其方法
提示:汽車的當前方向(東南西北)以及轉盤轉向(左右)可以分別用兩個枚舉表示。每次加速減速的值為定值,速度不能為負值,也不能超過最大速度。
3. (**)定義幾何類Geometry
用一個方法同時計算矩形的面積和體積,並同時返回它的面積和體積
 
4.(**)買房是大事:
 
1) 創建兩個類,模擬生活中房屋和人的特征和行為。
房屋類:
    特征:房東、地址、面積、每平米價格
    行為:估價、升值等
(提示:房屋的房東是人類;估價返回 面積*每平米價格;升值改變 每平米價格)
人類:
    特征:姓名、性別、錢、配偶、房子
    行為:工作掙錢、買房子、結婚、賣房子、離婚等
(提示:人類的配偶是人類;買房子的參數是房子類)
 
(2) 在Main方法中運用以上兩個類創建(實力化)對象模擬以下情景:
一個人工作掙錢,有一天終於攢夠了錢,買了一個房子,然后找了一個對象結婚。
后來婚姻出現了第三者,兩人離婚后此人賣掉了房子,最終和第三者結婚。
/*4.(**)買房是大事:
 
1) 創建兩個類,模擬生活中房屋和人的特征和行為。
房屋類:
    特征:房東、地址、面積、每平米價格
    行為:估價、升值等
(提示:房屋的房東是人類;估價返回 面積*每平米價格;升值改變 每平米價格)
人類:
    特征:姓名、性別、錢、配偶、房子
    行為:工作掙錢、買房子、結婚、賣房子、離婚等
(提示:人類的配偶是人類;買房子的參數是房子類)
 
(2) 在Main方法中運用以上兩個類創建(實力化)對象模擬以下情景:
一個人工作掙錢,有一天終於攢夠了錢,買了一個房子,然后找了一個對象結婚。
后來婚姻出現了第三者,兩人離婚后此人賣掉了房子,最終和第三者結婚。
*/
namespace  BuyHouse
{
     enum Sex
    {
        男,女
    }
     class Person
    {
         public string Name { get; set; }        //姓名,屬性
         public Sex PersonSex { get; set; }      //性別,屬性
         public double Money { get; set; }       //錢,屬性
         public Person Mate { get; set; }        //配偶,屬性
         public House PersonHouse { get; set; }  //房子,屬性
         public void PersonInit(string name, Sex sex, double money, Person mate, House house)
        {
            Name = name;
            PersonSex = sex;
            Money = money;
            Mate = mate;
            PersonHouse = house;
        }
         /// <summary>
         /// 掙錢
         /// </summary>
         /// <param name=" m"></param>
         public void EarnMoney(double m)
        {
            Money += m;
             Console.WriteLine("你當前的存款為:{0}" ,Money);
        }
         /// <summary>
         /// 買房子
         /// </summary>
         public void BuyHouse(House house)
        {
             //存款大於等於房子總價格
             if (Money>=house.TotalPrice)
            {
                house.Host =  this;//this調用的
                 Console.WriteLine("你買到了房子,房東是:{0}" ,this.Name);
                 //房子買到了,存款減去房子總價格
                PersonHouse = house;
                Money -= house.TotalPrice;
            }
             else
            {
                 Console.WriteLine("你的存款不夠,需要掙錢買房子" );
            }
        }
         public void Marry(Person girl)
        {
             if (PersonHouse==null )
            {
                 Console.WriteLine("房子都沒有,不能結婚" );
            }
             else
            {
                Mate = girl;
                girl.Mate =  this;
                 Console.WriteLine("我結婚了,配偶的名字是:{0}" ,girl.Name);
            }
        }
         public void SaleHouse()
        {
             Console.WriteLine("把房子賣了" );
            Money += PersonHouse.TotalPrice;
            PersonHouse.Host =  null;
            PersonHouse =  null;
             Console.WriteLine("賣房后的存款為:{0}" ,Money);
        }
         public void Divorce()
        {
             this.Mate.Mate = null ;
            Mate =  null;
             Console.WriteLine("離婚了,做個單身狗" );
        }
 
    }
     class House
    {
         public Person Host { get; set; }        //房東,屬性
         public string Address { get; set; }     //地址,屬性
         public double Area { get; set; }        //面積,屬性
         public double Price { get; set; }       //價格,屬性
         /// <summary>
         /// 初始化房子
         /// </summary>
         /// <param name=" host"></param>
         /// <param name=" add"></param>
         /// <param name=" area"></param>
         /// <param name=" pri"></param>
         public void HouseInit(Person host, string add,double area,double price)
        {
            Host = host;
            Address = add;
            Price = price;
            Area = area;
        }
         public double TotalPrice { get; set; }  //房子總價
         /// <summary>
         /// 給房子估價
         /// </summary>
         public void Evaluate()
        {
            TotalPrice = Area * Price;
        }
         /// <summary>
         /// 房價升值
         /// </summary>
         /// <param name=" up"></param>
         public void PriceUp(double up)
        {
            Price = up;
        }
 
    }
 
     class Program
    {
         static void Main(string[] args)
        {
             House house = new House();
            house.HouseInit(  null, "清河" , 100.4, 7.5);
             Person lilei = new Person();
            lilei.PersonInit(  "李雷",Sex .男,0,null,null);
             Person hanmeimei = new Person();
            hanmeimei.PersonInit(  "韓梅梅" , Sex.女, 0, null, null );
            lilei.BuyHouse(house);
            house.Evaluate();
            lilei.BuyHouse(house);
            lilei.EarnMoney(400);
            lilei.Marry(hanmeimei);
            lilei.BuyHouse(house);
            lilei.EarnMoney(400);
            lilei.BuyHouse(house);
            lilei.Marry(hanmeimei);
            house.PriceUp(8);
            house.Evaluate();
            lilei.SaleHouse();
            lilei.Divorce();
 
             Console.ReadKey();
        }
    }
}

 

作業,類 對象方法

作者: 574096324@qq.com
 1.(*)完成課件的練習,建30個類,每個類有自己的特征,為特征填寫Get 方法和Set方法。
2. (***)完成藍鷗班級開班儀式流程:
1、早9:30開班儀式開始。(輸出(“開班儀式正式開始”))2、劉輝老師做自我介紹。3、三名學生做自我介紹。
需求:
  (1)定義一個班級類。
成員:所屬培訓機構名稱,班級名,班級人數、授課老師名字、開班日期。
方法:初始化(設置學校名字:藍鷗)、集體活動、開班儀式。
  (2)定義一個老師類。
成員:名字、性別、年齡、正在教的課程、正在授課班級。
方法:初始化、講課、布置作業、驗收作業、解決問題、自我介紹。
  (3)定義一個學生類。
成員:名字、性別、年齡、學號、班級名、任課老師、正在學習的課程。
方法:初始化、學習、做作業、提出問題、回答問題、自我介紹。
3.(**)創建一個方法,功能是把一個int類型的數組拷貝到另外一個數組里面,並把數組各元素打印出來;
4.(**)創建一個方法,求一個int類型數組里面元素的和,並把和打印出來;

 

類和面向對象編程

作者: 574096324@qq.com
類,對象,類成員:字段、方法
 
 //用類創建一個對象,用new運算符,類里面用來描述特征的變量稱為這個類的字段
            //Car car = new Car();
            ////使用對象調用字段時,用點運算符得到字段並賦值,
            ////如果在類外部使用字段時,字段一定用public修飾
            //car.color = "red";
            //car.price = 100.5;
            //car.type = "BMW";
            ////用點運算符點出來的成員,前面如果是
            ////F表示的是字段(field),M表示的是方法,C表示類,E表示枚舉,S代表結構體,
            ////D表示委托,I表示接口,'{'表示名字空間,P表示屬性
  ////API)(Application Program Interface)應用程序開發接口

 

作業

作者: 574096324@qq.com
1. (***)定義一個枚舉類型PlayerStatus(包括:跑run,跳jump,下滑sliding,左轉彎turnLeft,右轉彎turnRight),用來表示玩家的動作,結合switch/case語句使用,寫一個小程序:按W跑,空格跳,S下滑,A左轉彎,D右轉變.
2. (*)定義一個枚舉類型PrimitiveType(包括:正方體 cube,球體 sphere,膠囊體 capsule,圓柱體cylinder,平面plane,四邊形quad),用來存在常用的游戲物體。定義一個枚舉變量並賦值,輸出其默認的整型值。
3. (**)結構體排序:定義一個結構體Vector3(包括x,y,z三個公共成員變量,float類型),聲明3個結構體變量,按照x由小到大得排序規則(x相同的則按照y排,y相同則按照z排序),依次輸出三個變量。
4. (***)某班有5個學生,三門課(數學,英語和語文)。分別實現以下要求: 
(1) 求各門課的平均分; 
(2) 找出有兩門以上不及格的學生,並輸出其學號和不及格課程的成績; 
(3) 找出三門課平均成績在85-90分的學生,並輸出其學號和姓名 ;
(4)按成績對學生進行降序排序,如果數學成績相等,按英語成績排序,如果英語成績相等,按語文成績排序;
5.(**)用枚舉表示網購訂單狀態,輸入推進狀態數,模擬訂單進展過程,並顯示最終狀態。訂單狀態參考: 未確認,已確認,已取消,無效,未發貨,已發貨,未付款,已付款,退貨,確認收貨,完成。
6. (**)創建一個英雄結構體變量,成員包含英雄當前狀態。
     英雄的可以有名字,HP,MP等屬性
7. (***)用結構體數組創建創建兩個戰隊(每隊5人),為每個英雄賦隨機屬性,合算綜合戰斗力並輸出
      提示:戰斗力可以是平均等級,攻擊力,血量等等。也可以是由這些數值構成的一個綜合表達式
 
 
using  System;
 
namespace  第05課件
{
     class MainClass
    {
         //課堂練習1的枚舉
         enum Action
        {
            Run = 1,
            Jump,
            Idel = 4,
            Attack,
        }
         //課堂練習2的枚舉
         enum GameStatus
        {
             //開始
            Start,
             //暫停
            Pause,
             //結束
            Over
        }
         //課堂練習3的結構體
         public struct StudentInfor
        {
             public string name;
             public int age;
             public int number;
        }
         //課后作業1的枚舉
         enum PlayerStatus
        {
            run = 119,
            jump = 32,
            sliding = 115,
            turnLeft = 97,
            turnRight = 100
        }
         //課后作業2的枚舉
         enum PrimitiveType
        {
             //正方體
            cube = 6,
             //球體
            sphere = 0,
             //膠囊體
            capsule = 1,
             //圓柱體
            cylinder = 2,
             //平面
            plane = 5,
             //四邊形
            quad = 4
        }
         //課后作業3的結構 體
         struct Vector3
        {
             public float x;
             public float y;
             public float z;
        }
         //課后作業4的結構體
         struct Student
        {
             public string name;
             public int number;
             public float math;
             public float english;
             public float music;
        }
         //課后作業5的枚舉
         enum ShoppingStatus
        {
            未確認,
            已確認,
            已取消,
            無效,
            未發貨,
            已發貨,
            未付款,
            已付款,
            退貨,
            確認收貨,
            完成訂單
        }
         //課后作業6的結構體
         struct Hero
        {
             public string name;
             public int HP;
             public int MP;
             public PlayerStatus status;
        }
         //課后作業7的結構體
         struct HeroAttackValue
        {
 
             public int attack;
        }
 
         public static void Main( string[] args)
        {
           
             /*
                                                //課堂練習1:創建枚舉,表⽰一個人體的各類動作,並賦予其不同的內部整數值,觀察其他枚舉直接量內部整數值的變化。
                                                //以枚舉Action為例,把Jump和Attack的值打印出來
                                                Action a = Action.Jump;
                                                int n1 = (int)a;
                                                Console.WriteLine ("Jump的值是:{0}",n1);
                                                Action b = Action.Attack;
                                                int n2 = (int)b;
                                                Console.WriteLine ("Jump的值是:{0}",n2);
                                                */
 
 
             //課堂練習2:創建枚舉,表⽰示游戲的所有狀態(開始游戲、暫停游戲、結束游戲)
             //答案見上面
 
 
             /*
                                                //課堂練習3:創建學⽣生結構體,包含姓名、年齡、學號等信息,並賦予其值,輸出結構體成員的值。
                                                StudentInfor stu1;
                                                stu1.name = "張三";
                                                stu1.age = 24;
                                                stu1.number = 20140101;
                                                Console.WriteLine ("學生的姓名:{0},年齡:{1},學號:{2}",stu1.name,stu1.age,stu1.number);
                                                */
 
 
             /*
                                                //課后作業1:定義一個枚舉類型PlayerStatus(包括:跑run,跳jump,下滑sliding,
                                                //左轉彎turnLeft,右轉彎turnRight),用來表示玩家的動作,結合switch/case語句使用,寫一個小程序
                                                do {
                                                                Console.WriteLine ("請按下相應的鍵:(a向左,d向右,s滑動,w跑,空格跳)");
                                                                Console.Write("\n");
                                                                PlayerStatus p = (PlayerStatus)Console.Read();
                                                                switch(p){
                                                                case PlayerStatus.run :
                                                                                {
                                                                                Console.WriteLine("跑");
                                                                                break;
                                                                                }
                                                                case PlayerStatus.jump :
                                                                                {
                                                                                Console.WriteLine("跳");
                                                                                break;
                                                                                }
                                                                case PlayerStatus.sliding :
                                                                                {
                                                                                Console.WriteLine("滑動");
                                                                                break;
                                                                                }
                                                
                                                                case PlayerStatus.turnLeft :
                                                                                {
                                                                                Console.WriteLine("左轉");
                                                                                break;
                                                                                }
                                                                case PlayerStatus.turnRight :
                                                                                {
                                                                                Console.WriteLine("右轉");
                                                                                break;
                                                                                }
                                                                default:
                                                                                {
                                                                                Console.WriteLine("退出");
                                                                                break;
                                                                                }
                                                                }
                                                } while(true);
                                                */
 
 
             /*
                                                //課后作業2:定義一個枚舉類型PrimitiveType(包括:正方體 cube,球體 sphere,膠囊體 capsule,
                                                //圓柱體cylinder,平面plane,四邊形quad),用來存在常用的游戲物體。定義一個枚舉變量並賦值,
                                                //輸出其默認的整型值。
                                                Console.WriteLine ("正方體的值為:{0}",(int)PrimitiveType.cube);
                                                Console.WriteLine ("球體的值為:{0}",(int)PrimitiveType.sphere);
                                                Console.WriteLine ("膠囊體的值為:{0}",(int)PrimitiveType.capsule);
                                                Console.WriteLine ("圓柱體的值為:{0}",(int)PrimitiveType.cylinder);
                                                Console.WriteLine ("平面的值為:{0}",(int)PrimitiveType.plane);
                                                Console.WriteLine ("四邊形的值為:{0}",(int)PrimitiveType.quad);
                                                */
 
 
             /*
                                                //課后作業3:結構體排序:定義一個結構體Vector3(包括x,y,z三個公共成員變量,float類型),
                                                //聲明3個結構體變量,按照x由小到大得排序規則(x相同的則按照y排,y相同則按照z排序),
                                                //依次輸出三個變量。
                                                //定義三個結構體變量,分別賦值
                                                Vector3 vec1;
                                                vec1.x = 12;
                                                vec1.y = 13;
                                                vec1.z = 35;
                                                Vector3 vec2;
                                                vec2.x = 45;
                                                vec2.y = 14;
                                                vec2.z = 34;
                                                Vector3 vec3;
                                                vec3.x = 45;
                                                vec3.y = 23;
                                                vec3.z = 25;
                                                //把結構體放到數組里面進行冒泡排序,只是比較數據的時候用的是結構體里面的成員
                                                Vector3[] v = { vec1, vec2, vec3 };
                                                for (int i = 0; i < v.Length; i++) {
                                                                for (int j = 0; j < v.Length - i - 1; j++) {
                                                                                //數組元素是一個結構體,得到數組元素的值后,再訪問結構體里面的成員數據
                                                                                //然后用成員數據進行比較
                                                                                if (v [j].x < v [j + 1].x) {
                                                                                                Vector3 temp = v [j];
                                                                                                v [j] = v [j + 1];
                                                                                                v [j + 1] = temp;
                                                                                }
                                                                                if (v [j].x == v [j + 1].x) {
                                                                                                if (v [j].y < v [j + 1].y) {
                                                                                                                Vector3 temp1 = v [j];
                                                                                                                v [j] = v [j + 1];
                                                                                                                v [j + 1] = temp1;
                                                                                                }
                                                                                                if (v [j].y == v [j + 1].y) {
                                                                                                                if (v [j].z < v [j + 1].z) {
                                                                                                                                Vector3 temp2 = v [j];
                                                                                                                                v [j] = v [j + 1];
                                                                                                                                v [j + 1] = temp2;
                                                                                                                }
                                                                                                }
                                                                                }
                                                                }
                                                }
                                                //把排序后的結構體數據打印出來
                                                for (int i = 0; i < 3; i++) {
                                                                Console.Write ("{0},{1},{2}\n", v [i].x, v [i].y, v [i].z);
                                                }
                                                */
 
 
           
             //課后作業4:某班有5個學生,三門課。分別實現以下要求:
             //(1) 求各門課的平均分;
             //(2) 找出有兩門以上不及格的學生,並輸出其學號和不及格課程的成績;
             //(3) 找出三門課平均成績在85-90分的學生,並輸出其學號和姓名
             //提示:定義五個學生的結構體,並賦值,然后把其放到數組里面進行操作
             //本題答案的值全部固定了,目的是讓學生多練習,另外大家可以試着把它放到循環里面
             Student stu1;
             Student stu2;
             Student stu3;
             Student stu4;
             Student stu5;
             //給五個結構體變量賦值
             //第一個學生信息
            stu1.name =  "張三";
            stu1.number = 20140101;
            stu1.math = 56;
            stu1.english = 98;
            stu1.music = 78;
 
             //第二個學生信息
            stu2.name =  "李四";
            stu2.number = 20140102;
            stu2.math = 95;
            stu2.english = 34;
            stu2.music = 80;
             //第三個學生信息
            stu3.name =  "王五";
            stu3.number = 20140103;
            stu3.math = 90;
            stu3.english = 55;
            stu3.music = 43;
             //第四個學生信息
            stu4.name =  "趙六";
            stu4.number = 20140104;
            stu4.math = 89;
            stu4.english = 67;
            stu4.music = 78;
             //第五個學生信息
            stu5.name =  "周八";
            stu5.number = 20140105;
            stu5.math = 86;
            stu5.english = 87;
            stu5.music = 85;
             //定義一個結構體數組
             Student[] s = { stu1, stu2, stu3, stu4, stu5 };
             //求各門課的平均值
             float aver1 = 0;
             float sum1 = 0;
             float aver2 = 0;
             float sum2 = 0;
             float aver3;
             float sum3 = 0;
             for (int i = 0; i < s.Length; i++)
            {
                sum1 += s[i].math;
                sum2 += s[i].english;
                sum3 += s[i].music;
            }
            aver1 = sum1 / s.Length;
            aver2 = sum2 / s.Length;
            aver3 = sum3 / s.Length;
             Console.WriteLine("數學的平均分數是:{0}" , aver1);
             Console.WriteLine("英語的平均分數是:{0}" , aver2);
             Console.WriteLine("音樂的平均分數是:{0}" , aver3);
             //找出有兩門不及格成績的學生,並把學號和不級格的成績打印出來
             for (int i = 0; i < s.Length; i++)
            {
                                                                
                 if (s[i].english < 60 && s[i].math < 60 && s[i].music < 60)
                {
 
                }
                 else
                {
                     if (s[i].math < 60 && s[i].english < 60)
                    {
                         Console.Write(@"不及格學生的學號為:{0},不及格的成績為:數學{1},英語{2}" ,
                            s[i].number, s[i].math, s[i].english);
                         if (s[i].music < 60)
                        {
                             Console.WriteLine(@"不及格學生的學號為:{0},不及格的成績為:數學{1},英語{2}" ,
                                s[i].number, s[i].math, s[i].english);
                        }
                    }
                     if (s[i].math < 60 && s[i].music < 60)
                    {
                         Console.WriteLine(@"不及格學生的學號為:{0},不及格的成績為:數學{1},音樂{2}" ,
                            s[i].number, s[i].math, s[i].music);
                    }
                     if (s[i].music < 60 && s[i].english < 60)
                    {
                         Console.WriteLine(@"不及格學生的學號為:{0},不及格的成績為:音樂{1},英語{2}" ,
                            s[i].number, s[i].music, s[i].english);
                    }
                }
            }
             //找出三門課平均成績在85-90分的學生,並輸出其學號和姓名
             float sumTotal = 0;
             float avreTotal = 0;
             for (int i = 0; i < s.Length; i++)
            {
                sumTotal = s[i].math + s[i].english + s[i].music;
                avreTotal = sumTotal / 3;
                 if (avreTotal >= 85 && avreTotal <= 90)
                {
                     Console.WriteLine("三門平均成績在85-90的學生是:{0},{1}" , s[i].name, s[i].number);
                }
            }
 
 
 
             /*
                                                //課后作業5:用枚舉表示網購訂單狀態,輸入推進狀態數,模擬訂單進展過程,並顯示最終狀態。
                                                //訂單狀態參考: 未確認,已確認,已取消,無效,未發貨,已發貨,未付款,已付款,退貨,確認收貨,完成。
                                                ShoppingStatus[] s = new ShoppingStatus[11];
                                                Console.WriteLine ("請輸入狀態值:");
                                                int input = Convert.ToInt32 (Console.ReadLine());
                                                for (int i = 0; i < s.Length; i++) {
                                                                s [i] = (ShoppingStatus)i;
                                                }
                                                for (int i = 0; i < input; i++) {
                                                                Console.Write ("{0},",s[i]);
                                                }
                                                */
 
 
             /*
                                                //課后作業6:創建一個英雄結構體變量,成員包含英雄當前狀態。英雄的可以有名字,HP,MP等屬性
                                                Hero hero;
                                                hero.name = "李四";
                                                hero.HP = 90;
                                                hero.MP = 100;
                                                */
 
 
             /*
                                                //課后作業7:用結構體數組創建兩個戰隊(每隊5人),為每個英雄賦隨機屬性,合算綜合戰斗力並輸出
                                                //提示:戰斗力可以是平均等級,攻擊力,血量等等。也可以是由這些數值構成的一個綜合表達式
                                                HeroAttackValue[] h1 = new HeroAttackValue[5];
                                                HeroAttackValue[] h2 = new HeroAttackValue[5];
 
                                                Console.WriteLine ("請輸入第1隊各成員的攻擊值:");
                                                int sum1 = 0;
                                                                for (int j = 0; j < 5; j++) {
                                                                h1 [j].attack = Convert.ToInt32 (Console.ReadLine());
                                                                sum1 += h1 [j].attack;
                                                                }
 
                                                Console.WriteLine ("請輸入第2隊各成員的攻擊值:");
                                                int sum2 = 0;
                                                for (int j = 0; j < 5; j++) {
                                                                h2 [j].attack = Convert.ToInt32 (Console.ReadLine());
                                                                sum2 += h2 [j].attack;
                                                }
                                                Console.WriteLine ("第1隊的綜合戰斗力為{0}:",sum1);
                                                Console.WriteLine ("第2隊的綜合戰斗力為{0}:",sum2);
                                                */
                                
                                                                                                
 
        }
    }
}

 

結構體訪問修飾符

作者: 574096324@qq.com
 
            如果在類和結構體里面,成員前面不加任何修飾符,則該成員是private的,
            表示在類或者結構體的外部不能點出來的私有成員
            如果在名字空間下定義的類或者結果體,默認的訪問級別是internal的,
            表示只能在改名字空間內部使用外部不能使用;
            跨類、名字空間用public
            internal在名字空間內使用

 

二維數組

作者: 574096324@qq.com
//將一個二維數組的行和列交換,存儲到另外一個數組中
             //int[,] a = new int[2, 3] { { 1, 2 ,3},{ 4, 5, 6 } };
            // int[,] b = new int[a.GetLength(1), a.GetLength(0)];
            // for (int i = 0; i < b.GetLength(0); i++)
            // {
            //     for (int j = 0; j < b.GetLength(1); j++)
            //     {
            //         b[i, j] = a[j, i];
            //         Console.Write(b[i,j]+" ");
            //     }
            //     Console.WriteLine();
            //}
//有個3行4列的二維數組,求最大元素以及所在的行和列
             //int[,] a = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
             //int max, row, line;
             //max = a[0,0];
             //row = 0;
             //line = 0;
             //for (int i = 0; i < a.GetLength(0); i++)
             //{
             //    for (int j = 0; j < a.GetLength(1); j++)
             //    {
             //        if (max < a[i, j])
             //        {
             //            max = a[i, j];
             //            row = i;
             //            line = j;
             //        }
             //    }
             //}
             //Console.WriteLine("max={0},行號是{1},列號是{2}", max, row+1, line+1);
           賦值一個二維數組
//int[,] a = new int[4, 3];
             //for (int i = 0; i < a.GetLength(0); i++)
             //{
             //    Console.WriteLine("請輸入第{0}行賦值的數",i);
             //    for (int j = 0; j < a.GetLength(1); j++)
             //    {
             //        a[i, j] = int.Parse(Console.ReadLine());
             //    }
 
             //}
             //Console.ReadKey();
             ////打印數組
             //Console.WriteLine("打印賦值的數組");
             //for (int i = 0; i < a.GetLength(0); i++)
             //{
             //    for (int j = 0; j < a.GetLength(1); j++)
             //    {
             //        Console.Write(a[i, j] + " ");
             //    }
             //    Console.WriteLine();
             //}
 
             //Console.WriteLine("第一行元素");
             //for (int i = 0; i < a.GetLength(1); i++)
             //{
             //    Console.Write(a[0, i] + " ");
             //}
             //Console.WriteLine("和");
             //int sum = 0;
             //for (int i = 0; i < a.GetLength(1); i++)
             //{
             //    sum += a[1, i];
             //}
             //Console.WriteLine("sum=" + sum);

 

04作業

作者: 574096324@qq.com
 1.(**)從控制台先輸入你一個整數n,表示之后會輸入n個年齡.
將結果按由大到小排序輸出.例如:
請輸入n:
3
請輸入3個年齡:
28
31
19
結果為:
31,28,19
2.(**)求一個4階數字矩陣(數值隨機產生)對角線的和,如;
1   2   3   4
5   6   7   8
9  10  11  12
13 14  15  16
輸出: 69.
3.(***)輸入一個n,隨機生成一個n*n的二維數組地圖,數組元素值隨機產生.完成如下操作.例如輸入3,
自動生成:
1 2 3 
4 5 6
7 8 9
1)求下三角元素的和.(上例為1+4+5+7+8+9=34)
2)遍歷二維數組,如果二維數組元素值為偶數,將元素更新為’*’,如果為奇數,將元素更新為’ #’.
# * #
* # *
# * #
3)將上圖看做一個游戲地圖(#為二維坐標系0,0點),輸入一個x,y值,將元素更改為’$’.
例如:輸入(0,0),輸出
# * #
* # *
$ * #
4.(***)聲明一個二維數組,存放游戲玩家可以行走的四個方向(前后左右),假如游戲玩家在二維坐標系的原點,按下w/s/a/d(不區分大小寫)代表前后左右,循環輸入字符,輸出游戲玩家的位置;

 

數組

作者: 574096324@qq.com
數組定義,數組初始化:動態初始化,靜態初始化
int[ ] array=new int[6];   new 是運算符;數值類型初始值為0,bool類型是false,字符串初始值null.
動態初始化:數據類型[] 數組名=new 數據類型[數組長度]{元素1,元素2};
//數組的動態初始化
             int[] array = new int[6] { 1, 2, 3, 4, 5, 6 };
             int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6 };
             //數組的靜態初始化,只能寫在一行
             //int[] arr2 = { 7, 8, 9, 10, 11, 12 };
             //int i = 0;
             //Console.WriteLine(arr1[i]);
             //i++;
             //Console.WriteLine(arr1[i]);
             //Console.WriteLine(arr1.Length);
             for (int i = 0; i < arr1.Length; i++)
            {
                 Console.WriteLine(arr1[i]);
            }
   Console.ReadKey();
 

 

03循環數組作業

作者: 574096324@qq.com
作業;
1、(*)編程將所有“水仙花數”打印出來,並打印其總個數。 “水仙花數”是一個 各個位立方之和等於該整數的三位數。
2、(**)找出下列整型數組中最大和最小值及其所在位置i。
int[] a={3,5,8,13,47,9};
int[] b ={-23,45,14,65};
3、(***)給定某年某月某日,輸出其為這一年的第幾天。
4、(**)已知abc+cba = 1333,其中a,b,c均為一位數,編程求出滿足條件的a,b,c所有組合。
5、(***)輸入兩個數,求最大公約數和最小公倍數。(用兩種方法:輾轉相除法和普通方法)。
6、(****)輸入n,分別用*輸出邊長為n的實心菱形和空心菱形。
例如:n = 3時,輸出:
  *
 ***
*****
 ***
  *
 
  *
 * *
*   *
 * *
  *
7. 分別用while、do...while、for循環打印1~100之間3的倍數
8. 用while和for循環打印出1-100之間7的倍數,個位為7的數,十位為7的倍數,不是7的倍數並且不包含7
9. 使用嵌套循環產生下列圖案:
$
$$
$$$
$$$$
$$$$$
PPT上的練習
1.分別用靜態初始化和動態初始化定義一個具有5個元素的整型數組,並求數組元素的和。
2.將上面聲明的2個數組對應元素相加,放到另外一個數組中。
3.復制一個數組,即兩個數組容量一樣,把其中一個數組中的元素復制到另外一個數組中。
 

 

循環結構

作者: 574096324@qq.com
//定義一個變量記錄圈數,循環變量初始化
  int i = 0;
//執行循環的條件即循環條件
 while (i < 10)
 {
 Console.WriteLine("跑" + i);
 i++;
//i是循環變量
//條件越來越不滿足,最終跳出循環
}
//for(循環變量初始化;條件判斷;循環變量變化)
{
//循環體
}Console.WriteLine("{0,2}",i);前面2個空格,-2后面兩個空格(左對齊)
//外層行數,內層是行的內容
for (int j = 1; j < 4; j++)
            {
                for (int i = 1; i < 4; i++)
                {
                    Console .Write("{0,-2}" , i);
                }
                Console .WriteLine();
            }
/九九乘法表
for (int i = 1; i <= 9; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console .Write("{0}*{1}={2,-3}" , j, i,i*j);
                }
                Console .WriteLine();
            }
            Console .ReadKey();
循環總結:
for最常用,通常用於知道循環次數的循環
while也很常用,通常用於不知道循環次數的循環
do……while不是很常用,通常用於需要先執行一次的循環
break跳出本層循環,continue結束本次循環,通常與if連用
for()中定義的變量只作用於循環體{ }中。

 

02作業

作者: 574096324@qq.com
1、(*)編寫一個程序,要求用戶從鍵盤輸入2個float數據,輸出最大者.
2、(**)編寫一個程序,要求用戶從鍵盤輸入3個不同整數,輸出中間者.
3、(**)從鍵盤輸入兩個實數a和b,代表兩點在X軸的坐標,再輸入一個0到1之間的數c,代表時間,(假如從a到b需要1s),輸出在時間c時的坐標.
例如:輸入a為1和b為5,再輸入c為0.5,則輸出結果為:3.
4、(**)輸入一個成績(0到100之間的整數),如果大於等於90輸出:優秀;小於90而大於等於80輸出:良好;小於80而大於等於70輸出:一般;小於70而大於等於60輸出:及格,否則輸出:不及格.
5、(***)輸入一個生日日期,輸出其星座.
6.(*)輸入一個整數,判斷奇偶,並輸出“某某是奇數”或者“某某是偶數”。

7.(*)輸入一個數,判斷符號。如果大於0,輸出“正數”;如果小於0,輸出“負數”;如果等於0,輸出“0”。


8.(**)有一個函數:x<1的時候,y = x;1<=x<10的時候,y=2x-1;x>=10的時候,y=3x-11。寫一段程序,輸入x,輸出y值

9.(***)輸入3個數,判斷是否能構成三角形
10. (**)編制一個完成兩個數四則運算程序。如:用戶輸入34+56則輸出結果為90.00,要求運算結果保留2位有效小數,用戶輸入時將2個運算數以及運算符都輸入,根據運算符求結果

 

switch case

作者: 574096324@qq.com
switch (date)
            {
                case 1:
                    Console .WriteLine("周一" );
                    break ;
                case 2:
                    Console .WriteLine("周二" );
                    break ;
                case 3:
                    Console .WriteLine("周三" );
                    break ;
                case 4:
                    Console .WriteLine("周四" );
                    break ;
                case 5:
                    Console .WriteLine("周五" );
                    break ;
                case 6:
                    Console .WriteLine("周六" );
                    break ;
                case 7:
                    Console .WriteLine("周日" );
                    break ;
                default :
                    Console .WriteLine("大保健" );
                    break ;
            }
1.switch里面可以沒有default語句塊,如果所有的case都不符合要求時
            會直接跳出switch開關
            2.如果case后面有語句,則一定要有break
            3.如果case后面沒有任何代碼,它會和他后面的case共用一段代碼
            4.default的位置是隨意的
            5.case的位置不確定

 

語句結構

作者: 574096324@qq.com
順序
分支(if)
程序在運行時發現的錯誤,稱為異常(try catch finally)
try
{
char input = Convert.ToChar(Console.ReadLine());
if (input == 'm')
Console.WriteLine("男性");
else
 Console.WriteLine("女性");
}
catch
{
Console.WriteLine("你輸入的數據有問題");
 }
finally {
 }

 

分支結構

作者: 425369880@qq.com
if語句
if(條件表達式){
          語句1;
}esle if{
          語句2;
}esle{
          語句3;
}
級聯式if語句
 
值為bool類型的表達式
跳出是指跳出if后的一個{}
 
 

 
 
 
 
 

 
 
 
 

 

運算符,邏輯運算

作者: 574096324@qq.com
               int a = 3, b = 5;
            bool result = (a < b);
            Console .WriteLine(result);
            //比較兩數是否相等用==
            bool s = a == b;
            Console .WriteLine(s);
            //比較兩數是否不相等用!=
            bool s1 = a != b;
            Console .WriteLine(s1);
            //邏輯與&&,只有當前后數據都是true的時候,整個邏輯與的值是true
            //邏輯與只要其中一個值為false,整個邏輯表達式的值為false
            int age = 23;
            int age1 = 21;
            bool res = (age >= 22) && (age1 >= 20);
            Console .WriteLine(res);
            //邏輯或||只有||兩邊的值都是false,整個邏輯或的表達式的值才是false
            //如果其中一個值是true,邏輯表達式的結果也是true
            res = age >= 22 || ++age1 <= 20; //age1值還是21
            Console .WriteLine(res);
            //邏輯非!,取反
            Console .WriteLine(!res);
            //邏輯表達式的短路現象
            bool res1 = age <= 22 && ++age1 > 20;
            Console .WriteLine("age={0},age1={1}" ,age,age1); //age1值還是21

 

基本輸入、輸出函數

作者: 574096324@qq.com
//輸入方法,以回車鍵作為結束標志,得到的是從鍵盤上輸入的字符串
string input = Console .ReadLine();
Console .WriteLine(input);
//得到的是從鍵盤上輸入的第一個字符的ASC碼值
int cou = Console .Read();
Console .WriteLine(cou);
換行 Console.WriteLine();
格式化輸出,{}為占位符,{}里面的數字對應的是后面變量的序號,變量的序號從0開始依次遞增
int n1 = 2, n2 = 3, n3 = 4;
Console.WriteLine("n1={0},n2={1},n3={2}",n1,n2,n3);
               float score = 23.5f;
            //f表示小數點后保留幾位,后面可以加數字
            Console .WriteLine("score={0:F2}" ,score);
            Console .WriteLine("score={0:000.000}" ,score);
            //把數據轉換成%形式,並保留兩個小數位
            Console .WriteLine("{0:p2}" , 1 / 4f);
            //如果字符串前面加@,則字符串里面的轉義字符失效
            Console .Write(@"lanoukeji\n" );
            Console .Write("hello world" );
/*數據類型轉換
            1.隱式轉換,用在都是數值類型的兩個數據之間;
            轉換的條件:從取值范圍小的往范圍大的類型轉換,從精確度低往精確度高轉,兩個條件同時滿足
            2.強制類型轉換
            (1)使用類型轉換符
            (2)把字符串轉換成其它格式有兩種方法,第一種是Convert,第二種是Parse
            */
            int a = 10;
            float s = a;
            //類型轉換符轉換
            float f = 23.5f;
            int b = (int )f;
            //把字符串轉換成其它格式
            string str1 = "123" ;
            //Convert方法
            //轉成int類型
             int r1 = Convert .ToInt32(str1);
            //轉成float類型
            float f2 = Convert .ToSingle(str1);
            //Parse方法
             int r2 = int .Parse(str1);
            Console .WriteLine(str1);
char c= (char )99;
Console.WriteLine(c);
課后作業:
1、(*)打印下面圖形:
*
* *
* * *
2、(*)編寫一個程序,要求用戶輸入一個美元數量,然后顯示出增加%5稅率后的相應金額。格式如下所示:
Enter an amount:100.00
With tax added:$105.00
3、(*)從鍵盤輸入兩個實數a和b,輸出a占b的百分之幾。小數點后保留2位。
例如:輸入1和4,輸出:25.00%
4、(**)編寫一個程序,要求用戶輸入一個美金數量, 然后顯示出如何用最少的20美元、10美元、5美元和1美元來付款:
    Enter a dollar amout:93
    $20  bills: 4
    $10  bills: 1
    $5   bills:0
$1   bills:3
5、(*)輸入兩個整數,打印這兩個數的和,差,積,余數。
6、(*)查找ASCII碼表,輸入一個字符,輸出其ASCII碼。
 

 

常量,變量,運算符

作者: 574096324@qq.com
注釋,單行,多行,注釋函數
定義變量,
交換兩個int變量的值(int a,int b)
/int c;c=a;a=b;b=c;
/a=a+b;b=a-b;a=a-b;
變量命名規則:
1.相同變量名不能重復定義
2.只能包含數字,字母,下划線,並且數字不能開頭
3.區分大小寫,num,Num
4.不能使用關鍵字
5.見名知義
6.駱駝命名法,如果變量名只有一個單詞,則該單詞全部小寫,如果有兩個以上單詞,從第二個單詞開始每個單詞首字母大寫
7.@符號只能放在最前面,並且后面不能跟數字
運算符
把常量/變量與運算符組合起來的式子叫表達式
+用在字符串之間,作用是連接兩個字符串
++運算符單獨放在一行時,與上面一行代碼功能相同,都是把變量的值加1,++在前和在后功能也一樣
++在前先++,++在后后++
 當其不單獨在一行時
++在先是先把變量的值加1,之后再把變量參與到運算里面;
++在后是先把變量的值參與到運算里面,運算完了以后在把變量的值加1
復合運算符 a+=b;
 


免責聲明!

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



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