Unity (64bit) - Test3.unity - New Unity Project 55 - PC, Mac & Linux Standalone DX11  


// 回傳 Color32 版本

using UnityEngine;
using System.Collections;

public class Test3 : MonoBehaviour {

[Range(-3.14f, 3.14f)]
public float rotate = 0;

public Texture2D texToDraw;
private Texture2D newTexture;

void Update () {
if(newTexture != null){
Destroy(newTexture);
}


newTexture = new Texture2D (texToDraw.width, texToDraw.height);

newTexture.SetPixels32 (RotateSquare(texToDraw.GetPixels32(), rotate));
newTexture.Apply ();
}

Color32 [] RotateSquare(Color32[] arr, float phi){
int x;
int y;
int i;
int j;
float sn = Mathf.Sin(phi);
float cs = Mathf.Cos(phi);
Texture2D texture = Instantiate(texToDraw);
Color32[] arr2 = texture.GetPixels32();
int W = texture.width;
int H = texture.height;
int xc = W/2;
int yc = H/2;

for (j=0; j<H; j++){
for (i=0; i<W; i++){
arr2[j*W+i] = new Color32(0,0,0,0);

x = (int)(cs*(i-xc)+sn*(j-yc)+xc);
y = (int)(-sn*(i-xc)+cs*(j-yc)+yc);

if ((x>-1) && (x<W) &&(y>-1) && (y<H)){
arr2[j*W+i]=arr[y*W+x];
}
}
}
return arr2;
}

void OnGUI(){
GUI.DrawTexture (new Rect (10, 10, 100, 100), texToDraw);
GUI.DrawTexture (new Rect (120, 10, 100, 100), newTexture);
}

}


// 回傳 Texture 版本


using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    [Range(-360360)]
    public float rotate = 0;
    
    public Texture2D texToDraw;
    private Texture2D newTexture;
    
    void Update () {
        if(newTexture != null){
            Destroy(newTexture);
        }

        newTexture = RotateSquare (texToDrawrotate);
    }
    
    Texture2D RotateSquare(Texture2D texturefloat eulerAngles){
        int x;
        int y;
        int i;
        int j;
        float phi = eulerAngles/(180/Mathf.PI);
        float sn = Mathf.Sin(phi);
        float cs = Mathf.Cos(phi);
        Color32[] arr = texture.GetPixels32();
        Color32[] arr2 = new Color32[arr.Length];
        int W = texture.width;
        int H = texture.height;
        int xc = W/2;
        int yc = H/2;
        
        for (j=0j<Hj++){
            for (i=0i<Wi++){
                arr2[j*W+i] = new Color32(0,0,0,0);
                
                x = (int)(cs*(i-xc)+sn*(j-yc)+xc);
                y = (int)(-sn*(i-xc)+cs*(j-yc)+yc);
                
                if ((x>-1) && (x<W) &&(y>-1) && (y<H)){ 
                    arr2[j*W+i]=arr[y*W+x];
                }
            }
        }

        Texture2D newImg = new Texture2D (WH);
        newImg.SetPixels32 (arr2);
        newImg.Apply();

        return newImg;
    }
    
    void OnGUI(){
        GUI.DrawTexture (new Rect (1010100100), texToDraw);
        GUI.DrawTexture (new Rect (12010100100), newTexture);
    }
    
}

    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()