0
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?

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

0
Posted at

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
0
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
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?