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?

More than 1 year has passed since last update.

子オブジェクトを滑らかに回転させる [Unity2D]

Last updated at Posted at 2022-12-25

親オブジェクトが急激に回転した場合に、滑らかにその回転を追従するようなスクリプトを作ります。

実装

SmoothRotator.cs
using UnityEngine;

public class SmoothRotator : MonoBehaviour
{
    public bool SmoothRotate = true;
    public float SmoothTime = 0.1f;

    [SerializeField] private Transform rotateTarget;

    // Read-only
    [SerializeField] private float prevAngle;
    // Read-only
    [SerializeField] private float smoothVel;

    private void Update()
    {
        if (SmoothRotate && rotateTarget.parent is { } parent)
        {
            var currentAngles = rotateTarget.eulerAngles;
            currentAngles.z = prevAngle;
            // 親の角度
            var targetAngle = parent.eulerAngles.z;
            currentAngles.z = Mathf.SmoothDampAngle(currentAngles.z, targetAngle, ref smoothVel, SmoothTime);
            rotateTarget.rotation = Quaternion.Euler(currentAngles);
            prevAngle = currentAngles.z;
        }
        else
        {
            prevAngle = rotateTarget.eulerAngles.z;
            smoothVel = 0f;
        }
    }
}

使い方

滑らかに回転させたいGameObjectにアタッチします。
スクリーンショット 2022-12-26 0.14.25.png
こんな感じで親オブジェクトの回転に滑らかに追従するようになります。
Rotate.gif

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?