跳到正文
Qiita · Unity 开发社区· 来源· renren1027·· 2 小时前AI 评分1

Unity 中使用 UniTask 实现物体往复移动的方法

[Unity] 物体を往復させたい時用の簡単な方法

正文 · 原文

0

Go to list of users who liked

0

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

UniTaskが入っていること前提になります。

[Header("片道の長さ")]
[Selializefield]private float _length = 3f;
[Header("速さ")]
[Selializefield]private float _speed = 2f;

private async UniTask PingPongMove()
{
    float time = 0;
    Vector3 firstDistance = transform.position;

    while(true)
    {
    time += _speed * Time.deltaTime;
    var offset = Mathf.PingPong(time, _length);
    var currentDistance = firstDistance.x + offset;
    transform.position = new(currentDistance, firstDistance.y, firstDistance.z);
    await UniTask.Yield(PlayerLoopTiming.Update, this.GetCancellationTokenOnDestroy());
    }  
}

何かを往復させたい時に使えるコード。
_speedには動く速さ、_lengthには往復時の片道の長さを入れます。
後はPingPongMove.Forget();を好きなところで呼び出しましょう。

0

Go to list of users who liked

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme

What you can do with signing up

0

Go to list of users who liked

0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

来源:Qiita · Unity 开发社区 · qiita.com