0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】好きな補間関数で追従するカメラ

Posted at

はじめに

ネットで調べても意外にもヒットしなかったのでとりあえず作ってみた。
なんかかなり行き当たりばったりで作ったので、色々雑です。
本当は追従対象が動いている時は別で処理をすべきでなんですが、まあなんか面倒なので更新されたベクトルを使って
適当に補間させてます。よくない。

あと例によって私は素人です。

ソース


using UnityEngine;

namespace MyTool
{
    public class FollowUpCamera : MonoBehaviour
    {
        [SerializeField] GameObject _mainCamera;
        [SerializeField] GameObject _target;
        [SerializeField] AnimationCurve _animationCurve;
        [SerializeField] float _followUpTime = 3.0f;
        private float _elapsedTime;
        private Vector3 _relativeFollowingPosition;
        private Vector3 _currentTargetPosition;
        private Vector3 _currentCameraPosition;
        void Awake()
        {
            _relativeFollowingPosition = _mainCamera.transform.position - _target.transform.position;
            _currentTargetPosition = _target.transform.position;
            _currentCameraPosition = _mainCamera.transform.position;
        }
        void LateUpdate()
        {
            //動いているときだけ更新する
            if(_currentTargetPosition!=_target.transform.position)
            {
                _currentTargetPosition = _target.transform.position;
                _currentCameraPosition = _mainCamera.transform.position;
                _elapsedTime = 0f;
            }

            _elapsedTime += Time.deltaTime;
            _mainCamera.transform.position 
            = Vector3.Lerp(_currentCameraPosition, _currentTargetPosition + _relativeFollowingPosition, InterpolationFunction(_elapsedTime/_followUpTime));
        }
        private float InterpolationFunction(float rate)
        {
            return _animationCurve.Evaluate(rate);
        }
    }
}

_followUpTime秒で補間されます。
別に真新しいことはしていないです。補間関数にAnimationCurveを指定しているというだけです。
ぐにゃぐにゃな関数を指定するとぐにゃぐにゃ動きます。

独り言

巷じゃ、カメラが滑らかに追従するテンプレが出回ってるとおもうんですが、あれってどうなんだろう(今更)
なんか、Lerpの引数が毎フレーム変わるのって出力が明示的じゃないからあんまよくない気がする。
でもいい感じに動くのは確か。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?