「ややこしいUnityの座標系の確認方法」シリーズ. UnityのTexture2DクラスのLoadImage関数を使って画像をオブジェクトのテスクチャとして用いることができる. このテスクチャには当然テクスチャ座標が存在して,画像ファイルの画素の座標と,テクスチャ座標の関係もやはりマニュアルには明記されていない. これも簡単に実験で確認できるので記録しておく.
C#コード
Texture2D texture;
void Start()
{
texture = new Texture2D(1024, 1024, TextureFormat.BGRA32, false);
byte[] bytes = File.ReadAllBytes("Assets/texture.jpg");
texture.LoadImage(bytes);
texture.Apply();
GetComponent().material.mainTexture = texture;
}
void Update()
{
var material = this.GetComponent().material;
material.SetFloat("_width", (float)Screen.width);
material.SetFloat("_height", (float)Screen.height);
}
フラグメントシェーダ
float _width;
float _height;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, float2(i.vertex.x/_width, i.vertex.y/_height));
return col;
}
結果
つまり,画像の左下が原点(u,v)=(0,0),左上が(u,v)=(0,1),右下が(u,v)=(1,0)となるようにテクスチャ座標上に配置されたということ.

