unity笔记3 - Mathf.Repeat and Mathf.PingPong

版权声明:本文为博主原创文章,转载请注明源地址 https://blog.csdn.net/qq_15505341/article/details/79251558

Mathf.Repeat

定义
public static float Repeat(float t,float length);
循环值t,使输出不会大于等于length,也不会小于0。

        //输入 012345678
        //输出 012012012
        for (int i = 0; i < 9; i++)
        {
            Debug.Log(Mathf.Repeat(i,3));
        }

其实跟取模(%)的结果一样,但是取模的结果会有负数,Repeat的结果只会是整数
这里写图片描述


用Repeat改变Cube的坐标

    Vector3 start;
    float i = 0;
    // Use this for initialization
    void Start () {
        start = transform.position;
    }

    // Update is called once per frame
    void Update () {
        i += 0.1f;
        float l = Mathf.Repeat(i,5);
        transform.position = start + Vector3.left * l;
    }

因为用了Repeat,变量l的值只会在0-4.9之间循环循环循环,所以方块就一直循环循环的动了
这里写图片描述


Mathf.PingPong

定义
public static float PingPong(float t,float length);
循环值t,使输出不会大于length,也不会小于0。
返回值将在0和length之间来回移动。

        //输入012345678
        //输出012321012
        for (int i = 0; i < 9; i++)
        {
            Debug.Log(Mathf.PingPong(i,3));
        }

0123210123210123210,来回来回,乒乒乓乓
这里写图片描述


用PingPong改变Cube的坐标

    Vector3 start;
    float i = 0;
    // Use this for initialization
    void Start () {
        start = transform.position;
    }

    // Update is called once per frame
    void Update () {
        i += 0.1f;
        float l = Mathf.PingPong(i,5);
        transform.position = start + Vector3.left * l;
    }

因为用了PingPong,变量l的值只会在0-4.9之间来回来回,所以方块就一直来回来回的动了
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_15505341/article/details/79251558