簡體   English   中英

如何在 Unity 中更改 Sprite uv?

[英]How to change Sprite uv in Unity?

我寫了以下腳本:

public class SpriteUV : MonoBehaviour 
{
    private SpriteRenderer _spriteRenderer;
    private Sprite _sprite;

    [SerializeField] public Vector2[] _uv = new Vector2 [4]
    {
        new Vector2(0.4f, 0.5f),
        new Vector2(0.6f, 0.5f),
        new Vector2(0.4f, 0.35f),
        new Vector2(0.6f, 0.35f)
    }; 

    void Start ()
    {
        _spriteRenderer = GetComponent<SpriteRenderer>();
        _sprite = _spriteRenderer.sprite;
    }

    // Update is called once per frame
    void Update ()
    {
        _sprite.uv = _uv;
    }
}

但是這有一個錯誤,它表明Sprite.uv沒有設置器(文檔中不明顯)如何更改精靈以映射紋理的不同部分?

這是一個與SpriteRenderer一起使用的解決方案,用於至少選擇要顯示的 Sprite 的矩形部分。 (程序員如何在評論中正確指出,如果您需要完全不同的映射,這不會“變形”您的 UV。)

  1. 創建一個新的着色器並將其BlendVertexColorWithUV

  2. 在 VisualStudio(或任何文本編輯器)中打開它並輸入以下代碼
    來源

     // unlit, vertex color, alpha blended, offset uv's // cull off Shader "BlendVertexColorWithUV" { Properties { _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {} } SubShader { Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"} ZWrite Off Lighting Off Cull Off Fog { Mode Off } Blend SrcAlpha OneMinusSrcAlpha LOD 110 Pass { CGPROGRAM #pragma vertex vert_vct #pragma fragment frag_mult #pragma fragmentoption ARB_precision_hint_fastest #include "UnityCG.cginc" sampler2D _MainTex; float4 _MainTex_ST; struct vin_vct { float4 vertex : POSITION; float4 color : COLOR; float2 texcoord : TEXCOORD0; }; struct v2f_vct { float4 vertex : POSITION; fixed4 color : COLOR; float2 texcoord : TEXCOORD0; }; v2f_vct vert_vct(vin_vct v) { v2f_vct o; o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); o.color = v.color; o.texcoord = TRANSFORM_TEX (v.texcoord, _MainTex);; return o; } fixed4 frag_mult(v2f_vct i) : COLOR { fixed4 col = tex2D(_MainTex, i.texcoord) * i.color; return col; } ENDCG } } SubShader { Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"} ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off Fog { Mode Off } LOD 100 BindChannels { Bind "Vertex", vertex Bind "TexCoord", texcoord Bind "Color", color } Pass { Lighting Off SetTexture [_MainTex] { combine texture * primary } } } }
  3. 創建新材質

  4. BlendVertexColorWithUV拖動到該材質上

  5. 將此材質分配給使用SpriteRenderer的對象

  6. SpriteRendererDrawModeTiled

  7. TileMode設置為Continous

在此處輸入圖片說明

注意:我實際上在抓取時犯了一個錯誤:您將Sprite分配給SpriteRenderer而不是材料! 您實際上可以保留材質 Blanc,只需調整TilingOffset值。

現在您可以調整材質中精靈的偏移,例如使用腳本

public Material textureToAnimate;
public Vector2 uvOffset;

....

textureToAnimate.mainTextureOffset = uvOffset;

我剛剛使用了Quad ,您可以uvs設置uvsverticestriangles 所以基本上從 Sprite 獲取所有信息(uv,頂點)並將其傳輸到Quad

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM