饂飩コーディング

iOSアプリやら、Unityやら、Cocos2dやらごにょごにょ書いております

Offsetいじってテクスチャーを動かしてみよう。

サイトが引っ越しました。→https://scombu.com

約1秒後に自動的にリダイレクトします。切り替わらない場合はリンクをクリックしてください。

f:id:appdeappuappu:20181126212931p:plain

まずは下のリンクをクリックして実行結果をご覧ください
Unity WebGL Player | LearnC#


真ん中青いのやつ
1、Updateの中でフレームごとにテクスチャのオフセットを少しずつ変化させてます。
考え方も簡単。

public class nekoScript : MonoBehaviour {

    public Renderer rend;

    public float offsetDelta;
    public float offsetValue;

    // Use this for initialization
    void Start () {
        rend = gameObject.GetComponent<Renderer>();
        offsetDelta = 0.001f;
        offsetValue = 0.0f;
	}
	
	// Update is called once per frame
	void Update () {

        offsetValue = offsetValue + offsetDelta;
        rend.material.SetTextureOffset("_MainTex", new Vector2(0, offsetValue));

    }
}

次は左の赤い方
2、Time.deltaTimeに係数をかけてスピード調整してオフセットをいじってスクロールさせています。
これだと実行環境による速度に差があってもうまいことだいたい同じスピードになりそうです。
途中のoffsetValueの-1.0f調整は無くてもいいです。

public class nekoScript3 : MonoBehaviour
{
    public Renderer rend;
    public float offsetValue;
    public float speedFactor;

    // Use this for initialization
    void Start()
    {
        rend = gameObject.GetComponent<Renderer>();
        offsetValue = 0.0f;
        speedFactor = 0.1f;//スピード係数
    }

    // Update is called once per frame
    void Update()
    {
        offsetValue = offsetValue + Time.deltaTime * speedFactor;

        if(offsetValue >= 1.0f){
            offsetValue = offsetValue - 1.0f;
        }
        rend.material.SetTextureOffset("_MainTex", new Vector2(0, offsetValue));
    }
}


最後は、右の猫の後ろにブロックがないやつ
3、コルーチンを使ってスクロールさせてみたバージョン

public class nekoScript2 : MonoBehaviour
{
    public Renderer rend;
    public float value;

    // Use this for initialization
    void Start()
    {
        rend = gameObject.GetComponent<Renderer>();
        value = 0.0f;
        StartCoroutine(loop());
    }

    // Update is called once per frame
    void Update()
    {
    }
    private IEnumerator loop()
    {
        while (true)
        {
            yield return new WaitForSeconds(0.01f);
            onTimer();
        }
    }

    private void onTimer()
    {
        value = value + 0.001f;
        rend.material.SetTextureOffset("_MainTex", new Vector2(0, value));
        Debug.Log("on timer");
    }

}

↓使ったテクスチャーはこちら。
f:id:appdeappuappu:20181126214832p:plain