コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】SpringJoint2D を LineRenderer で表示するサンプル

ソースコード

using UnityEngine;

[DisallowMultipleComponent]
[ExecuteAlways]
[RequireComponent( typeof( SpringJoint2D ) )]
[RequireComponent( typeof( LineRenderer ) )]
public sealed class Example : MonoBehaviour
{
    private SpringJoint2D m_springJoint2D;
    private LineRenderer  m_lineRenderer;

    private void Awake()
    {
        m_springJoint2D = GetComponent<SpringJoint2D>();
        m_lineRenderer  = GetComponent<LineRenderer>();
    }

    private void Update()
    {
        var originPoint = transform.TransformPoint( m_springJoint2D.anchor );

        var connectedPoint = m_springJoint2D
            .connectedBody
            .transform
            .TransformPoint( m_springJoint2D.connectedAnchor );

        m_lineRenderer.SetPosition( 0, originPoint );
        m_lineRenderer.SetPosition( 1, connectedPoint );
    }
}

使用例

f:id:baba_s:20211114210158g:plain