何がしたいのか
Transform.SetParent
を使わずに、衝突したオブジェクトとの相対位置を一致させたい。
(こういうの。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が変化したことを考慮していません