Unity3D中如何用代码实现物体的左右循环移动?
Unity3D中用代码实现物体的左右循环移动的方式如下:
1、新建一个Cube,在Cube X轴的正方向放置一个空物体或者其他GameObject,Cube和空物体的Y值一致,确保2者在同一水平线上;
2、把下列代码保存为C#,赋给Cube,并在Inspector视图中,把空物体赋到脚本的PointB中;
using UnityEngine;
using System.Collections;
public class Moving : MonoBehaviour
{
public Transform PointB;
private int _direction = 1;
private float _pointA;
// Use this for initialization
IEnumerator Start ()
{
_pointA = transform.position.x;
while (true)
{
if (transform.position.x < _pointA)
{
_direction = 1;
}
if (transform.position.x > PointB.position.x)
{
_direction = -1;
}
transform.Translate(_direction * 2 * Time.deltaTime,0,0);
yield return 0;
}
}
}