// 回傳 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(-360, 360)]
public float rotate = 0;
public Texture2D texToDraw;
private Texture2D newTexture;
void Update () {
if(newTexture != null){
Destroy(newTexture);
}
newTexture = RotateSquare (texToDraw, rotate);
}
Texture2D RotateSquare(Texture2D texture, float 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=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];
}
}
}
Texture2D newImg = new Texture2D (W, H);
newImg.SetPixels32 (arr2);
newImg.Apply();
return newImg;
}
void OnGUI(){
GUI.DrawTexture (new Rect (10, 10, 100, 100), texToDraw);
GUI.DrawTexture (new Rect (120, 10, 100, 100), newTexture);
}
}