首先,給出聖典的解釋:
Material.mainTextureOffset 主紋理偏移量
var mainTextureOffset : Vector2
Description描述
The texture offset of the main texture.
主紋理中的紋理偏移量
The same as using GetTextureOffset or SetTextureOffset with "_MainTex" name.
這個與帶有"_MainTex"名稱的 GetTextureOffset 和 SetTextureOffset 相同
參考:SetTextureOffset, GetTextureOffset.
1 using UnityEngine; 2 using System.Collections; 3 4 public class example : MonoBehaviour 5 { 6 public float scrollSpeed = 0.5F; 7 void Update() 8 { 9 float offset = - Time.time * scrollSpeed; //這里的Time.time和我例子中 Time.detalTime不一樣 但這句話的意思是一樣的 都是不斷遞減的一個數 10 renderer.material.mainTextureOffset = new Vector2(offset, 0); 11 } 12 }
從上面我們知道,TextureOffset是紋理偏移的意思,通過renderer.material.mainTextureOffset = new Vector2(offset, 0);函數實現Unity中物體材質的偏移,
通過這個函數 可以在游戲中實現背景循環滾動的效果(也可以通過兩個相同的背景交替上下實現這個效果,這里不做細講) 我們知道編程中一個函數體不變的函數,能影響輸出結果
的就是函數的參數, 那么這個函數中的參數代表着什么呢?
筆者在Unity中進行試驗:
float m_offset; //物體材質的偏移量 float m_speed= 0.1f; //物體材質偏移的速度 void Update () { m_offset =m_offset - m_speed * Time.deltaTime; //這里物體材質的偏移量 就是 每幀的時間乘以自己定義的速度 this.GetComponent<Renderer>().material.mainTextureOffset = new Vector2(0, m_offset); //通過這個函數實現物體材質的偏移和滾動 }
!!!這里注意 材質偏移只有(x,y)兩個參數 分別代表材質在橫向和縱向的偏移!!!
在上述例子中,
1.我首先把 new Vector2(0, m_offset)中的0改為10000,編譯后在Unity中調試 發現物體材質的偏移速度並沒有發生改變
2.然后我又把 new Vector2(0, m_offset)中的0和m_offset進行了互換,發現由上下偏移變成了左右偏移,說明常量沒有效果 一個每幀都改變的量才能實現函數的偏移
3.我又把 1.步驟中加了一步:把m_offset前面乘以10000,這樣就變成了 new Vector2(10000, 10000*m_offset); 然后調試發現 物體材質偏移左右依然巋然不動 然后上下快了好多好多,
這說明函數中的"10000"是有效果的,而且只有在參數是變量的基礎上才會發生作用,而且10000變成100000000的話 物體材質偏移的速度會更快
這樣,我們對renderer.material.mainTextureOffset = new Vector2(offset, 0);就有一個全面深刻的了解了,以后用到也會更加靈活了.