多语言展示
当前在线:1931今日阅读:31今日分享:25

unity中实现物体的来回移动

实现方法非常简单
工具/原料

unity

方法/步骤
1

新建一个3d工程

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

点击运行,就可以看到结果了!

注意事项

注意layout部分要改成2 by 3!

推荐信息