Unity11--Unity界面Game面板上既有按钮,又有显示距离和计时、摆放位置规范

来源:互联网 发布:网络教育学校有区别吗 编辑:程序博客网 时间:2024/04/30 11:58

一、Unity界面Game面板上既有按钮,又有显示距离和计时(完整程序)

   //1.对应的代码                        ------------------------------ 写在最上边的程序

    string distanceStr ="距离:0";

    Vector3 startPosition;                                                //获取最初位置用的 

    //2进阶的计时器

    string timeText ="00:00:00";

1.void Start () {

        startPosition = transform.position;

}

 

//2对应的代码计时用的

      float timer = 0;

      int hour = 0;

      int minute = 0;

     int second = 0;

 

2.void Update () {

      

        timer += Time.deltaTime;

        if(timer >1)

        {

            second++;

            timer -= 1;

        }

        if(second>=60)

        {

            minute++;

            second = 0;

        }

        if(minute >=60)

        {

            hour++;

            minute = 0;

        }

        timeText = string.Format("{0:00}:{1:00}:{2:00}", hour, minute, second);

                   

        //1对应的代码

        transform.Translate(transform.forward *Time.deltaTime * 2);

    }


//下面的程序是通过按钮点击修改速度-可加速,顺便显示距离---做塔防游戏用的,控件

3.void OnGUI()//---记住这个

    {

        GUIStyle style =newGUIStyle();

        style.alignment = TextAnchor.MiddleCenter;  //格式是居中

        GUI.Label(newRect(Screen.width - 100, 0, 100, 60), timeText,style);//文本显示在右上角居中

          

        if (GUI.Button(newRect(0,0,60,40),"1倍速度"))//产生三个按钮

        {

            Time.timeScale = 1;

        }

 

        if (GUI.Button(newRect(0, 45, 60, 40), "2倍速度"))

        {

            Time.timeScale = 2;

        }

        if (GUI.Button(newRect(0, 90, 60, 40), "暂停"))

        {

            Time.timeScale = 0;

        }

        GUI.Label(newRect(65, 0, 100, 60), distanceStr);//在面板上加上显示移动的距离,写的是文本

        float distance =Vector3.Distance(startPosition,transform.position);

        distanceStr = "距离" + distance;

}

二、按钮的摆放位置规范

上面的代码用到的按钮位置安放必须记住规范使用

1.表示看到的都是Game面板的,摆控件,GUI的左上角是(0,0,0)点,鼠标的是左下角(000)点

   Debug.Log("屏幕的宽度" + Screen.width);  //理解与本题无关

  Debug.Log("屏幕的高度" + Screen.height);

2. 摆控件方法位置,按钮一直会在屏幕右下角,不会变动----理解记住--与本题无关

        if (GUI.Button(newRect(Screen.width - 100, Screen.height - 100, 100, 100),"Button"))

        {

        }

  2.1GUI.Label(newRect(Screen.width - 100, 0, 100, 60), "helloWorld");//文本显示在右上角写法