Страница 1 из 2

GUI вращение/Rotate GUI

СообщениеДобавлено: 08 апр 2009, 13:44
Fox Malder
Вот, если кому нада покрутить GUI и вместе с ним что-нибудь в сцене (как в Google Earth), юзаем...

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 08 апр 2009, 13:46
Neodrop
Спасибо, огромное!!! :ymhug:

Код: Выделить всё
using UnityEngine;
using System.Collections;

public class RotateArrowScript : MonoBehaviour {

  /// <summary>
    /// Put this on guiTexture (GameObject) and set Transform node to (t000,r000,s001);
    /// </summary>

   static public bool DownArrowObject=false;
   public Texture2D tex;// Texture manipulator
   float angle;//
   public GameObject RotateArrow;// Rotate object
   public GameObject mainCam;// Main Camera
   public float rSpeed=0.01f;// speed of rotate
   float iniAngle=0;// Initial angle of GUI
   Rect mainRect = new Rect(680,50,100,100); //Main rectangle of all GUI
   Vector3 centerOfGUI;//center point of GUI
   Vector3 centerRotateOfGUI;//center point of Rotate
   Vector3 defferenseVector;
   float vert;//Vertical sign
   float goriz;//Horizontal sign
   
   void Start(){
      mainCam=GameObject.Find("Main Camera") as GameObject;
      guiTexture.pixelInset=new Rect(mainRect.x,Screen.height-mainRect.y-mainRect.height,mainRect.width,mainRect.height);//Position of GUITexture
      centerOfGUI=new Vector3(mainRect.x+mainRect.width/2,Screen.height-mainRect.y-mainRect.height+mainRect.height/2,1);
      centerRotateOfGUI=new Vector2(mainRect.x+mainRect.width/2,mainRect.y+mainRect.height/2);
   }
   
   
   ////////////////////////////////////////////////
   /// Deactivate Camera
   ////////////////////////////////////////////////
   
   void OnMouseDown(){
   DownArrowObject=true;
   }
   
   void OnMouseUp(){
   DownArrowObject=false;
   mainCam.SendMessage("RenderToTexture");
   angle=0;
   }
   
   //////////////////////////////////////////////////
   
   
    void OnMouseDrag(){
    defferenseVector = Input.mousePosition-centerOfGUI;
    vert=Mathf.Clamp(defferenseVector.y,-1,1);// get sign
    goriz=Mathf.Clamp(defferenseVector.x,-1,1);
    angle=(Input.GetAxis("Mouse Drag X")*vert+(-Input.GetAxis("Mouse Drag Y"))*goriz)*rSpeed;
   RotateArrow.transform.Rotate(0,angle,0);
    }
   
    void OnGUI(){
       Matrix4x4 iniMatrix=GUI.matrix;
       
       iniAngle+=angle;
      GUIUtility.RotateAroundPivot(iniAngle,centerRotateOfGUI);//Change GUI matrix
      GUI.DrawTexture(mainRect,tex);
      
      ///There restore the initial GUI.matrix for future elements from iniMatrix;
      GUI.matrix=iniMatrix;
      
   }
}

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 08 апр 2009, 16:49
Neodrop
Вариант 2.

Код: Выделить всё
using UnityEngine;
using System.Collections;

public class RotateArrowScript : MonoBehaviour {
  /// <summary>
    /// Put this on guiTexture (GameObject) and set Transform node to (t000,r000,s001);
    /// </summary>
   static public bool DownArrowObject=false;
   public Texture2D tex;// Texture manipulator
   float angle;//
   public GameObject RotateArrow;// Rotate object
   public GameObject mainCam;// Main Camera
   public float rSpeed=0.01f;// speed of rotate
   float iniAngle=0;// Initial angle of GUI
   Rect mainRect;
   Vector3 centerOfGUI;//center point of GUI
   Vector3 centerRotateOfGUI;//center point of Rotate
   Vector3 defferenseVector;
   float vert;//Vertical sign
   float goriz;//Horizontal sign
   
   
   void Start(){
      mainCam=GameObject.Find("Main Camera") as GameObject;
      mainRect = guiTexture.pixelInset; mainRect.y = Screen.height - mainRect.y-mainRect.height;
      centerOfGUI=new Vector3(mainRect.x+mainRect.width/2,Screen.height-mainRect.y+mainRect.height/2,1);
      centerRotateOfGUI=new Vector2(mainRect.x+mainRect.width/2,mainRect.y+mainRect.height/2);
   }
   
   
   ////////////////////////////////////////////////
   /// Deactivate Camera
   ////////////////////////////////////////////////
   
   void OnMouseDown(){
   DownArrowObject=true;
   }
   
   void OnMouseUp(){
   DownArrowObject=false;
   angle=0;
   }
   
   //////////////////////////////////////////////////
   
   
    void OnMouseDrag(){
    defferenseVector = Input.mousePosition-centerOfGUI;
    vert=Mathf.Clamp(defferenseVector.y,-1,1);// get sign
    goriz=Mathf.Clamp(defferenseVector.x,-1,1);
    angle=(Input.GetAxis("Mouse X")*vert+(-Input.GetAxis("Mouse Y"))*goriz)*rSpeed;
   
    }
   
    void OnGUI(){
       Matrix4x4 iniMatrix=GUI.matrix;
       
       iniAngle+=angle;
      GUIUtility.RotateAroundPivot(iniAngle,centerRotateOfGUI);//Change GUI matrix
      GUI.DrawTexture(mainRect,tex);
      RotateArrow.transform.Rotate(0,0,angle);
      ///There restore the initial GUI.matrix for future elements from iniMatrix;
      GUI.matrix=iniMatrix;
      
   }
}

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 08 апр 2009, 20:36
Neodrop
Вариант 3. Добавлен ресет по двойному клику на текстуре.

Код: Выделить всё
using UnityEngine;
using System.Collections;

public class RotateArrowScript : MonoBehaviour {
  /// <summary>
    /// Put this on guiTexture (GameObject) and set Transform node to (t000,r000,s001);
    /// </summary>
   static public bool DownArrowObject=false;
   public Texture2D tex;// Texture manipulator
   float angle;//
   public GameObject RotateArrow;// Rotate object
   public GameObject mainCam;// Main Camera
   public float rSpeed=0.01f;// speed of rotate
   float iniAngle=0;// Initial angle of GUI
   Rect mainRect = new Rect(680,50,74,74); //Main rectangle of all GUI
   Vector3 centerOfGUI;//center point of GUI
   Vector3 centerRotateOfGUI;//center point of Rotate
   Vector3 defferenseVector;
   float vert;//Vertical sign
   float goriz;//Horizontal sign
   static public bool reset = false;
   
   bool clicked = false;
   float lastClickedTime = 0.0f;
   
   Quaternion resetRot;
   
   void Start(){
      mainCam=GameObject.Find("Main Camera") as GameObject;
      mainRect = guiTexture.pixelInset; mainRect.y = Screen.height - mainRect.y-mainRect.height;
      centerOfGUI=new Vector3(mainRect.x+mainRect.width/2,Screen.height-mainRect.y+mainRect.height/2,1);
      centerRotateOfGUI=new Vector2(mainRect.x+mainRect.width/2,mainRect.y+mainRect.height/2);
      resetRot = RotateArrow.transform.rotation;
   }
   
   public static void DoubleClick()
   {
      if (DownArrowObject) reset = true;
   }
   
   
   ////////////////////////////////////////////////
   /// Deactivate Camera
   ////////////////////////////////////////////////
   
   void OnMouseDown(){
   DownArrowObject=true;
   if(clicked)
        {         
            if (Time.time - lastClickedTime > 0.5f)
            {
                 //too long, so set this as a first click
                 clicked = true;
                 lastClickedTime = Time.time;
            }
            else
            {
                 //it was a double click!
                 clicked = false;
                 lastClickedTime = 0.0f;
                 DoubleClick();
            }
        }
        else
        {
            clicked = true;
            lastClickedTime = Time.time;
        }
   }
   
   void OnMouseUp(){
   DownArrowObject=false;
   angle=0;
   }
   
   //////////////////////////////////////////////////
   
   
    void OnMouseDrag(){
    defferenseVector = Input.mousePosition-centerOfGUI;
    vert=Mathf.Clamp(defferenseVector.y,-1,1);// get sign
    goriz=Mathf.Clamp(defferenseVector.x,-1,1);
    angle=(Input.GetAxis("Mouse X")*vert+(-Input.GetAxis("Mouse Y"))*goriz)*rSpeed;
   
    }
   
    void OnGUI(){
       Matrix4x4 iniMatrix=GUI.matrix;
       if (!reset)
      {
         iniAngle+=angle;
         GUIUtility.RotateAroundPivot(iniAngle,centerRotateOfGUI);//Change GUI matrix
         
         GUI.DrawTexture(mainRect,tex);
         RotateArrow.transform.Rotate(0,0,angle);
         ///There restore the initial GUI.matrix for future elements from iniMatrix;
         GUI.matrix=iniMatrix;
         return;
      }
      iniAngle=0;
      GUIUtility.RotateAroundPivot(0,centerRotateOfGUI);//Change GUI matrix
      GUI.DrawTexture(mainRect,tex);
      GUI.matrix=iniMatrix;
      
      RotateArrow.transform.rotation = resetRot;
      reset = false;
   }
}

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 09 апр 2009, 12:59
fox
Вот упрощенный вариант, просто поворот текстуры на определенный угол

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;

public class RotateArrowScript : MonoBehaviour {
        public float angle;
        public Rect mainRect;
        public Texture guiTextur;
       
        Vector3 centerRotateOfGUI;//center point of Rotate
       
        void Start(){
        centerRotateOfGUI = new Vector2(mainRect.x + mainRect.width / 2, mainRect.y + mainRect.height / 2);
        }
   
        void OnGUI(){
        Matrix4x4 iniMatrix = GUI.matrix;
        GUIUtility.RotateAroundPivot(angle, centerRotateOfGUI);//Change GUI matrix
        GUI.DrawTexture(mainRect, guiTextur);
        ///There restore the initial GUI.matrix for future elements from iniMatrix;
        GUI.matrix = iniMatrix;    
        }
}

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 11:46
janua
А как это поставить?
На GuiTexture пишет, что не ставит, копирую текстом просто в яваскрипт - выдает кучу ошибок.
Можно подробнее как сделать саму сцену с вращением, чтобы с привязкой к объекту?

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 16:51
janua
Переименовал скрипт в "Rotate Arrow Script" - теперь могу добавлять к объектам и выбирать в параметрах текстуру, объект и камеру, но все равно ничего не происходит и пишет одну ошибку:
"There are inconsistent line endings in the 'Assets/RotateArrowScript.cs' script. Some are Mac OS X (UNIX) and some are Windows.
This might lead to incorrect line numbers in stacktraces and compiler errors. Unitron and other text editors can fix this using Convert Line Endings"

Может, кто знает, чего с этим всем делать?

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 19:28
Serge
А нечего, что скрипт написан на шарпе, и что имя скрипта должно быть без пробелов? Научитесь сначала работать со скриптами, делать свои, потом уже беритесь за чужие. Каков вопрос, таков ответ.
Сообщение об ошибке, у вас кстати просто предупреждение, в полнее читаемо переводится любым переводчиком.

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 19:36
warr11r
Скопируйте текст в Блокнот, а затем обратно в чистый скрипт. Ваш интерпретатор смущает то, что строки заканчиваются разными типами перехода каретки на новую строку.

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 21:23
Neodrop
Не слушайте кривых советов. Line Ending настраивается в редакторе кода. Выставьте "Windows"
Где настраивается - это зависит от редактора кода. Если вы используете UniSciTE то ищите в Text (кажется). Если Visual Studio то "Файл-Дополнительные параметры сохранения"

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 10 мар 2010, 22:26
gnoblin
Serge злой :D .

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 11 мар 2010, 17:38
janua
О, пасибки, ошибки хоть исчезли! Я использую UniSciTE. Где меняется на Windows не нашел, но убрал все комменты и ошибок больше нет.
Только вот от этого ничего не изменилось.
Я создаю , Cube и GuiTexture, на последнюю накладываю данный скрипт, меняю параметры Transform в GUITexture на значения 000 - 000 - 001 (если я правильно понял "Transform node to (t000,r000,s001)"). Во вкладке параметров скрипта для "Rotate Arrow" ставлю Cube, а для Main Cam соответственно Main Camera. С параметром "Tex" я вообще не знаю что делать потому, что чего бы я туда не совал - отображается только та карта, что выбрана в параметрах самой GUITexture.
А при нажатии на Play вижу куб, естественно и текстуру, что установлена для GUITexture. Но она никак не функционирует...

Напишите, плиз, юнцу чего не так и как его найдо делать-то!

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 11 мар 2010, 19:33
Serge
Выложите пример того, что сотворили, посмотрим, что не получается.
Кстати, про какой вариант скрипта идет речь? :)

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 14 мар 2010, 19:28
janua
спасибо всем! Уже разобрался.

Re: GUI вращение/Rotate GUI

СообщениеДобавлено: 14 мар 2010, 23:44
Neodrop
Добавить в название темы (РЕШЕНО)