9
8

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 5 years have passed since last update.

【Unity】 Transform.SetParentを使わずに子オブジェクトの相対位置を追従させたい

Posted at

何がしたいのか

Transform.SetParentを使わずに、衝突したオブジェクトとの相対位置を一致させたい。

rotation.gif
(こういうの。CubeとSphereはそれぞれ独立したオブジェクトだが、相対値を維持している。)

実装例

using UnityEngine;

public class AttachSample : MonoBehaviour
{
    /// <summary>
    /// 追従する対象
    /// </summary>
    private Transform _target;

    /// <summary>
    /// 相対位置
    /// </summary>
    private Vector3 _deltaPosition;

    /// <summary>
    /// 相対角度
    /// </summary>
    private Quaternion _deltaRotation;

    private void Update()
    {
        if (_target != null)
        {
            // 相対ベクトルにぶつかったときの角度の逆を反映してから、
            // 現在の角度を反映させる
            transform.position = _target.position + _target.rotation * _deltaRotation * _deltaPosition;
        }
    }

    /// <summary>
    /// 衝突したらくっつく
    /// </summary>
    /// <param name="other"></param>
    private void OnCollisionEnter(Collision other)
    {
        _target = other.transform;

        // 衝突したワールド座標
        var cp = other.contacts[0];

        // 対象の中心部から衝突地点への相対ベクトル
        _deltaPosition = cp.point - _target.position;

        // 対象の現在角度の「逆」
        _deltaRotation = Quaternion.Inverse(_target.rotation);
    }
}

備考

  • 追従する側の回転角は操作していません(位置のみ追従)
  • 対象のScaleが変化したことを考慮していません
9
8
1

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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?