Advertisement
Guest User

Unity_spacehip_project

a guest
Jul 26th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.89 KB | None | 0 0
  1. using System.Net;
  2. using System.Net.Sockets;
  3. using System.IO;
  4. using System;
  5. using System.Text;
  6. using System.Threading;
  7.  
  8. using UnityEngine;
  9. using System.Collections;
  10.  
  11. /**
  12.  * <summary>
  13.  * Класс космического зонда
  14.  * </summary>
  15.  * */
  16. public class SpaceShip
  17. {
  18.     private GameObject ship = GameObject.Find("Cube");;
  19.  
  20.     public SpaceShip()
  21.     {
  22.  
  23.     }
  24.  
  25.     public void UpatePosition(float x, float y, float z)
  26.     {
  27.         ship.transform.position = new Vector3(x, y, z);
  28.     }
  29.  
  30.     public void UpdateRotation(float a, float b, float g)
  31.     {
  32.         ship.transform.rotation = Quaternion.Euler(a, b, g);
  33.     }
  34.  
  35.     public Transform GetTransform()
  36.     {
  37.         return ship.transform;
  38.     }
  39. }
  40.  
  41. /**
  42.  * <summary>
  43.  * TCP-сервер, ожидает подключение единственного клиента. Запусткается в
  44.  * отдельном потоке.
  45.  * </summary>
  46.  * */
  47. public class ServerTCP {
  48.  
  49.     IPAddress Ip = IPAddress.Parse("127.0.0.1");
  50.     int Port = 9090;
  51.  
  52.     NetworkStream Stream;
  53.     TcpListener Server;
  54.     TcpClient Client;
  55.     Boolean Ready = false;
  56.  
  57.     float[] Data = new float[6];
  58.     Thread thread;
  59.  
  60.     public ServerTCP() {
  61.         thread = new Thread ( () => {
  62.             try {
  63.                 Server = new TcpListener (Ip, Port);
  64.                 Server.Start();
  65.  
  66.                 Debug.Log("Ожидание подключений... ");
  67.  
  68.                 Client = Server.AcceptTcpClient();
  69.                 Debug.Log("Подключен клиент.");
  70.  
  71.                 Stream = Client.GetStream();
  72.                 Ready = true;
  73.  
  74.                 while(true) {
  75.                     Read();
  76.                 }
  77.  
  78.             } catch (Exception e)
  79.             {
  80.                 Debug.Log("Socket error: " + e);
  81.             }
  82.  
  83.         });
  84.  
  85.         thread.Start ();
  86.     }
  87.  
  88.     public Boolean IsReady() {
  89.         return Ready;
  90.     }
  91.  
  92.     public float[] GetData() {
  93.         return Data;
  94.     }
  95.  
  96.     public void Close() {
  97.  
  98.         thread.Abort ();
  99.  
  100.         if (Stream != null) {
  101.             Stream.Close ();
  102.         }
  103.  
  104.         if (Client != null) {
  105.             Client.Close ();
  106.         }
  107.  
  108.         if (Server != null) {
  109.             Server.Stop ();
  110.         }
  111.    
  112.     }
  113.  
  114.     void Read()
  115.     {
  116.         Byte[] bytes = new Byte[4];
  117.  
  118.         for (int i = 0; i < 6; ++i) {
  119.             Stream.Read (bytes, 0, 4);
  120.             Data[i] = BitConverter.ToSingle(bytes, 0);
  121.             //Debug.Log(data[i]);
  122.         }
  123.  
  124.     }
  125. }
  126.  
  127. /**
  128.  * <summary>
  129.  * Базовый класс переключаемых камер. Паттерн "Состояние".
  130.  * </summary>
  131.  * */
  132. public class CameraBase {
  133.  
  134.     protected Camera C;
  135.     protected GameObject Ship = GameObject.Find("Cube");
  136.  
  137.     protected CameraBase (string CameraName) {
  138.         C = GameObject.Find(CameraName).GetComponent<Camera>();
  139.     }
  140.  
  141.     public void Activate() {
  142.         C.gameObject.SetActive (true);
  143.     }
  144.  
  145.     public void Deactivate() {
  146.         C.gameObject.SetActive (false);
  147.     }
  148.  
  149.     public virtual void Update() {
  150.  
  151.     }
  152. }
  153.  
  154. /**
  155.  * <summary>
  156.  * Камера, находящая позади космического зонда
  157.  * </summary>
  158.  * */
  159. public class CameraBack: CameraBase {
  160.  
  161.     public CameraBack(): base("Main Camera")  {
  162.         C.transform.SetParent (Ship.transform);
  163.     }
  164. }
  165.  
  166. /**
  167.  * <summary>
  168.  * Камера, находящая на носу космического зонда
  169.  * </summary>
  170.  * */
  171. public class CameraForvard: CameraBase {
  172.    
  173.     public CameraForvard(): base("Main Camera (1)")  {
  174.         C.transform.SetParent (Ship.transform);
  175.     }
  176. }
  177.  
  178. /**
  179.  * <summary>
  180.  * Камера, обеспечивающая свободный полет
  181.  * </summary>
  182.  * */
  183. public class CameraFly: CameraBase {
  184.  
  185.     float mouseSensitivity = 3.0f;
  186.     float speed = 15.0f;
  187.     Vector3 transfer;
  188.  
  189.     float minimumX = -360F;
  190.     float maximumX = 360F;
  191.     float minimumY = -60F;
  192.     float maximumY = 60F;
  193.     float rotationX = 0F;
  194.     float rotationY = 0F;
  195.     Quaternion originalRotation;
  196.    
  197.     public CameraFly(): base("CameraFly")  {
  198.         originalRotation = C.transform.rotation;
  199.     }
  200.  
  201.     public override void Update() {
  202.         rotationX += Input.GetAxis("Mouse X") * mouseSensitivity;
  203.         rotationY += Input.GetAxis("Mouse Y") * mouseSensitivity;
  204.  
  205.         rotationX = ClampAngle (rotationX, minimumX, maximumX);
  206.         rotationY = ClampAngle (rotationY, minimumY, maximumY);
  207.  
  208.         Quaternion xQ = Quaternion.AngleAxis (rotationX, Vector3.up);
  209.         Quaternion yQ = Quaternion.AngleAxis (rotationY, Vector3.left);
  210.         C.transform.rotation = originalRotation * xQ * yQ;
  211.  
  212.         // перемещение камеры
  213.         transfer = C.transform.forward * Input.GetAxis("Vertical");
  214.         transfer += C.transform.right * Input.GetAxis("Horizontal");
  215.         C.transform.position += transfer * speed * Time.deltaTime;
  216.     }
  217.  
  218.     public float ClampAngle (float angle, float min, float max)
  219.     {
  220.         if (angle < -360F) angle += 360F;
  221.         if (angle > 360F) angle -= 360F;
  222.         return Mathf.Clamp (angle, min, max);
  223.     }
  224. }
  225.  
  226. /**
  227.  * <summary>
  228.  * Камера, которая будет получать изображение, которое в дальнейшем должно быть
  229.  * обработано
  230.  * </summary>
  231.  * */
  232. public class CameraView {
  233.     protected Camera C = GameObject.Find("CameraView").GetComponent<Camera>();
  234.     protected GameObject Ship = GameObject.Find("Cube");
  235.  
  236.     public CameraView() {
  237.         C.transform.SetParent (Ship.transform);
  238.     }
  239.  
  240.     public Texture2D getTexture () {
  241.         RenderTexture currentRT = RenderTexture.active;
  242.         RenderTexture.active = C.targetTexture;
  243.         C.Render();
  244.  
  245.         Texture2D image = new Texture2D(C.targetTexture.width, C.targetTexture.height);
  246.         image.ReadPixels(new Rect(0, 0, C.targetTexture.width, C.targetTexture.height), 0, 0);
  247.         image.Apply();
  248.         RenderTexture.active = currentRT;
  249.         Debug.Log (image.EncodeToJPG().Length);
  250.         return image;
  251.     }
  252.        
  253. }
  254.  
  255. /**
  256.  * <summary>
  257.  * Класс-менеджер камер
  258.  * </summary>
  259.  * */
  260. public class CamarasManager {
  261.  
  262.     CameraBase CurrentCamera;
  263.  
  264.     CameraBack CBack = new CameraBack();
  265.     CameraForvard CForvard = new CameraForvard ();
  266.     CameraView CView = new CameraView();
  267.     CameraFly CFly = new CameraFly();
  268.  
  269.     public CamarasManager() {
  270.         CForvard.Deactivate ();
  271.         CFly.Deactivate ();
  272.         CurrentCamera = CBack;
  273.         getTexture ();
  274.     }
  275.  
  276.     public void Update () {
  277.         if (Input.GetKeyUp(KeyCode.Alpha1) && CurrentCamera != CBack) {
  278.             CurrentCamera.Deactivate ();
  279.             CurrentCamera = CBack;
  280.             CurrentCamera.Activate ();
  281.                
  282.         } else if (Input.GetKeyUp(KeyCode.Alpha2) && CurrentCamera != CForvard ) {
  283.             CurrentCamera.Deactivate ();
  284.             CurrentCamera = CForvard ;
  285.             CurrentCamera.Activate ();
  286.  
  287.         } else if (Input.GetKeyUp(KeyCode.Alpha3) && CurrentCamera != CFly ) {
  288.             CurrentCamera.Deactivate ();
  289.             CurrentCamera = CFly;
  290.             CurrentCamera.Activate ();
  291.  
  292.         }
  293.  
  294.         CurrentCamera.Update ();
  295.         //getTexture ();
  296.  
  297.     }
  298.  
  299.     public Texture2D getTexture () {
  300.         return CView.getTexture ();
  301.     }
  302.  
  303. }
  304.  
  305. public class test_1 : MonoBehaviour {
  306.  
  307.     ServerTCP Server;
  308.     SpaceShip Ship;
  309.     GameObject Particle;
  310.     CamarasManager CM;
  311.  
  312.     float x, y, z, a, b, g;
  313.  
  314.     void Start () {
  315.         Server = new ServerTCP();
  316.         Ship = new SpaceShip();
  317.         Particle = GameObject.Find("Particle System");
  318.  
  319.         CM = new CamarasManager ();
  320.     }
  321.  
  322.     void OnGUI() {
  323.         GUI.Label(new Rect(30, 30, 400, 60), "Для переключения камер используйте клавиши 1, 2, 3.\n" +
  324.             "Для Камеры 3 доступен свободный полет (WASD + мышь).");
  325.  
  326.         Color c = GUI.color;
  327.         if (Server.IsReady () ) {
  328.             GUI.color = Color.green;
  329.             GUI.Label(new Rect(30, 80, 400, 50), "Соединение с TCP-клиентом Simulink установлено");
  330.         } else {
  331.             GUI.color = Color.red;
  332.             GUI.Label(new Rect(30, 80, 200, 30), "Ожидание подключения simulink");
  333.         }
  334.         GUI.color = c;
  335.     }
  336.  
  337.     void Update () {
  338.         if (Server.IsReady ()) {
  339.             float[] data = Server.GetData ();
  340.             x = data [0];
  341.             y = data [1];
  342.             z = data [2];
  343.  
  344.             a = data [3];
  345.             b = data [4];
  346.             g = data [5];
  347.  
  348.             Ship.UpatePosition (x, y, z);
  349.             Ship.UpdateRotation (a, b, g);
  350.  
  351.             Particle.transform.position = new Vector3 (x - 2f, y, z - 0.75f);
  352.         }
  353.  
  354.         CM.Update ();
  355.     }
  356.  
  357.     void OnApplicationQuit() {
  358.         Server.Close ();
  359.     }
  360.  
  361. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement