如何将一个立方体在一个方向上移动3秒,然后在相反的方向上移动3秒,或者

问题描述

我不熟悉团结,可以尝试以下类似的方法,但是我只能朝一个方向移动,或者根本不移动。

我的多维数据集是一个触发器,并且没有使用重力。我已经选中了Kitematic框。我正在尝试使立方体来回移动,以便玩家难以收集。

using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class movedanger : MonoBehavIoUr
{
    private int mytime = 0;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        MyMover(mytime);
    }

    void MyMover(int mytime)
    {
      if (mytime <= 3)
        {
            transform.Translate(Vector3.forward * Time.deltaTime);
            mytime++;
        }

        else
        {
            transform.Translate(-Vector3.forward * Time.deltaTime);
            mytime = 1;
        }
    }
        
}

解决方法

您要寻找的是物体的来回运动。您可以使用Mathf.PingPong()函数来实现此目的,而不必使用翻译。我已经用一个多维数据集对其进行了测试,您可以设置它应该移动到的最小和最大距离以及它的移动速度。因为您希望多维数据集一次在一个方向上移动3秒。您可以将速度计算为距离/时间,以便根据当前距离和它所花费的时间(3秒)计算其应行驶的最大距离。希望这会有所帮助。

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

public class MoveCube : MonoBehaviour {
    public float min = 2f;
    public float max = 8f;
    public float SpeedOfMovement = 2f;
    // Start is called before the first frame update
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        transform.position = new Vector3 (Mathf.PingPong (Time.time * SpeedOfMovement,max - min) + min,transform.position.y,transform.position.z);
    }


}
,

使用InvokeRepeating,您将每3秒调用一次相同的MoveCube方法。

using UnityEngine;

public class MoveDanger: MonoBehaviour
{
    public bool isForward = false;

    private void Start()
    {
      
        InvokeRepeating("MoveCube",0f,3f);
    }

    private void MoveCube()
    {
        if (isForward)
        {
            transform.Translate(Vector3.back);
            isForward = false;
        }
        else
        {
            transform.Translate(Vector3.forward);
            isForward = true;
        }
    }
}
,

老实说,最好,最简单的方式是,一旦您习惯了,就可以做到

使用Unity极其简单的动画制作系统:

enter image description here

(基本上只需单击“新动画”,然后将其拖动到所需的位置即可。)

在线上有数百本教程介绍了如何使用它。

使用这些工具并查看它的简单性就是其中之一,您将进行“ facepalm”操作,而再也不会用其他方式打扰了。

这是实现目标的真正的“统一方式”,简单而灵活。