Unity 简单用C#实现物体左右循环移动

假设我在x轴的[-5,5]之间移动,话不多说,上代码:

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

public class NewBehaviourScript : MonoBehaviour {
    // Use this for initialization
    public float speed = 3f;
    private bool movingRight = true;
    void Start () {

    }
	
	// Update is called once per frame
	void FixedUpdate ()
    {
    //假设我在x轴-5到5之间左右循环移动
        if(movingRight)
        {
            //我正在右移
            transform.Translate(Vector3.right * speed * Time.deltaTime);

            //如果我移到了5,那么接下来就是左移,所以把右移设为false
            if (transform.position.x >= 5)
            {
                movingRight = false;
            }
        }
        else
        {
            //当我在左移,而且x轴坐标到了-5,说明结束左移,开始右移
            transform.Translate(Vector3.left * speed * Time.deltaTime);

            //左移结束,右移开始,设置状态为true
            if (transform.position.x <= -5)
            {
                movingRight = true;
            }
        }
	}
}

效果如图,脚本文件直接挂到你想要移动的平台上就行


版权声明:本文为csdn317341539原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。