unity3D中GUI标题内文字滚动效果

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class RollTxt : MonoBehaviour {
    //支持中文
    private string txt = "1234567werweerty74874651rtyrghdfgdgdfg891234wrew56789";
    public string showTxt;
    public int showLength = 8;
    public int txtLength;
    public float rollSpeed = 0.1f;
    private int indexMax;
    // Use this for initialization
    void Start () 
    {
        txtLength = txt.Length;
        showTxt = txt.Substring(0,showLength);
        indexMax = txtLength - showLength + 1;
    }

    // Update is called once per frame
    void Update () 
    {
        GetShowTxt();
    }

    void OnGUI()
    {
        GUI.Box(new Rect(200,200,150,20),showTxt);
    }

    void GetShowTxt() 
    {
        if(showLength>=txtLength)
        {
            showTxt = txt;
        }
        else if(showLength<txtLength)
        {
            int startIndex = 0;
            startIndex = (int)(Mathf.PingPong(Time.time * rollSpeed, 1) * indexMax);
            showTxt = txt.Substring(startIndex,showLength);
        }
    }
}

由于有的时候在GUI内输入一些文字标题的时候,标题的字符长度会超过我们排版要求的长度。有两种方法解决,第一种就是在超过的部分最后用“…”来代替,第二种就是让标题滚动起来。

第一种不做讨论,第二种还有一种方法,就是给GUI打组,然后动态修改组内标题GUI的X或Y的坐标,但是比较麻烦一些。

由于Mathf.PingPong(float t,float length);这个函数的来回动荡速度是和字符串的长度有关,所以要根据情况调整速度。

注意:Mathf.PingPong(float t,float length);unity官方给出的这个函数并不是我们想的那么好用,当length过大的时候会出现不受控制的情况,不知道为什么。解决方法就是把length全部写成1,在10以内还是没什么问题的,然后再后面乘以自己想要控制的数值。

 

posted @ 2013-09-23 11:32  Vital  阅读(3828)  评论(0编辑  收藏  举报