2024-05-17 09:26:55
Unity3D中用代码实现物体的左右循环移动的方式如下:
1、新建一个Cube,在CubeX轴的正方向放置一个空物体或者其他GameObject,Cube和空物体的Y值一致,确保2者在同一水平线上;
2、把下列代码保存为C#,赋给Cube,并在Inspector视图中,把空物体赋到脚本的PointB中;
usingUnityEngine;
usingSystem.Collections;
publicclassMoving:MonoBehaviour
{
publicTransformPointB;
privateint_direction=1;
privatefloat_pointA;
//Usethisforinitialization
IEnumeratorStart()
{
_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);
yieldreturn0;
}
}
}