カスタムスプライト(画像の中心を軸に回転縮小するGUIテクスチャ)のサンプル

using UnityEngine;
using System.Collections;

public class GUITest1 : MonoBehaviour {
  
   public Texture texture;
   CustumSprite custumSprite;
   
   // Use this for initialization
   void Start () {
       custumSprite = new CustumSprite();
       custumSprite.SetTexture(texture);
   }
   
   // Update is called once per frame
   void Update () {
   }
   
   float angle;
   float scale;
   float scaleTime;
   
   void OnGUI(){
       angle += Time.deltaTime * 20.0f % 3.14f; 
       scaleTime += Time.deltaTime;
       scale = 0.9f + Mathf.Sin(scaleTime)  * 0.1f;    //0.8f~1.0fの間をサインカーブで拡大縮小 
       
       custumSprite.SetPostion(new Vector3(400.0f , 100.0f ,0.0f));
       custumSprite.SetRotate(angle);
       custumSprite.SetScale(new Vector3(scale,scale,1.0f));
       custumSprite.Draw();
       
       custumSprite.SetPostion(new Vector3(100.0f , 100.0f ,0.0f));
       custumSprite.SetRotate(-angle);
       custumSprite.SetScale(new Vector3(scale,scale,1.0f));
       custumSprite.Draw();
       
   }
}

public class CustumSprite{

  public Texture texture;
   
   public Vector3 pivot;
   public Vector3 position;
   public Vector3 scale;
   public float angle;
   public Matrix4x4 matrix;
   
   Rect rect;
   bool updateMatrix;
   
   //ctor
   public CustumSprite()
   {
       this.pivot = Vector3.zero;
       this.position = Vector3.zero;
       this.scale = Vector3.one;
       this.angle = 0.0f;
       
       this.matrix = Matrix4x4.identity;
       this.rect = new Rect(0.0f,0.0f,1.0f,1.0f);
       this.updateMatrix = false;
   }
   
   public void SetTexture(Texture tex){
   
       this.texture=tex;
       
       if(texture!=null){
           this.pivot = new Vector3(texture.width/2,texture.height/2,0.0f);
       }
       else{
           Debug.Log("texture none");
       }
   }
   
   public void SetPostion (Vector3 pos)
   {
       this.position = pos;
       updateMatrix = true;
   }
   
   public void SetRotate (float angel)
   {
       this.angle = angel;
       updateMatrix = true;
   }

  public void SetScale (Vector3 scale)
   {
       this.scale = scale;
       updateMatrix = true;
   }

  public void Draw(){
       
       if(updateMatrix){
           //pivot処理 移動→回転→もとの位置に移動でピボットを中心に回転や拡大縮小をしているようになる 
           this.matrix = Matrix4x4.identity;
           
           this.matrix *= Matrix4x4.TRS(position,Quaternion.identity,Vector3.one);
           
           this.matrix *= Matrix4x4.TRS(pivot,Quaternion.identity,Vector3.one);
           this.matrix *= Matrix4x4.TRS(Vector3.zero,Quaternion.AngleAxis(angle,Vector3.forward),scale);
           this.matrix *= Matrix4x4.TRS(-pivot,Quaternion.identity,Vector3.one);
           
           GUI.matrix = this.matrix;
       }
       
       GUI.DrawTexture(new Rect(0,0,this.texture.width,this.texture.height),this.texture);
   }
}


メニュー



  • 最終更新:2014-06-13 12:13:16

このWIKIを編集するにはパスワード入力が必要です

認証パスワード