unity中实现物体的来回移动
1、新建一个3d工程
2、生成一个cube

3、生成一个脚本(名字要为move!!!)(右键生成选项)
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
private Transform son;
public bool moveToLeft = true;
private float speed = 2;
private void Start()
{
son = this.transform;
}
private void Update()
{
Move();
}
private void Move()
{
if (son.position.x <= -3 && moveToLeft)
{
moveToLeft = false;
}
else if (son.position.x >= 3 && !moveToLeft)
moveToLeft = true;
son.position += (moveToLeft ? Vector3.left : Vector3.right) * Time.deltaTime * speed;
}
}

4、将物体的相关脚本拖到层级视图新建的cube中

5、点击运行,就可以看到结果了!
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:122
阅读量:195
阅读量:46
阅读量:79
阅读量:27