unity3d 给移动的物体增加延迟?

ee7vknir  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(114)

我有一个向前和向后移动的物体,就在它即将向相反方向移动时,我试图在它再次移动之前添加一个非常短暂的延迟(1.0f)。

public class PushPlayer : MonoBehaviour
{
    public float moveAmount = 3.3f;
    public float speed = 1.1f;
    private Vector3 startPos;

    void Start()
    {
        startPos = transform.position;
    }

    void Update()
    {
        Vector3 v = startPos;
        v.z += moveAmount * Mathf.Sin(Time.time * speed);
        transform.position = v;
    }

}

我尝试用两种不同的方式实现一个协程,其中一种不起作用,另一种使我的整个游戏基本上冻结。我尝试再次调用该方法,我不确定是否有效,但没有结果。

swvgeqrz

swvgeqrz1#

using System.Collections;
using UnityEngine;

public class PushPlayer : MonoBehaviour
{
    public float moveAmount = 3.3f;
    public float speed = 1.1f;
    private Vector3 startPos;

    [SerializeField] private float _delay = 1f;

    void Start()
    {
        startPos = transform.position;

        StartCoroutine(DoMoving());
    }

    private IEnumerator DoMoving()
    {
        while (true)
        {
            yield return DoCycle();
            yield return new WaitForSeconds(_delay);
        }

        IEnumerator DoCycle()
        {
            var time = 0f;

            while (time * speed < Mathf.PI * 2f)
            {
                Vector3 v = startPos;
                v.z += moveAmount * Mathf.Sin(time * speed);
                transform.position = v;

                yield return null;
                time += Time.deltaTime;
            }
        }
    }
}

但最好使用dotween或dotween + unitask进行异步移动

相关问题