コガネブログ

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

【Unity】線と線の当たり判定を実装できる「Unity-LineSegmentsIntersection」紹介

はじめに

「Unity-LineSegmentsIntersection」を Unity プロジェクトに導入することで
線と線の当たり判定を実装できるようになります

使用例

using LineSegmentsIntersection;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        // 1本目の線
        var p1 = new Vector2( -1, 0 );
        var p2 = new Vector2( 1, 0 );

        // 2本目の線
        var p3 = new Vector2( 0, -1 );
        var p4 = new Vector2( 0, 1 );

        if ( Math2d.LineSegmentsIntersection( p1, p2, p3, p4, out Vector2 intersection ) )
        {
            Debug.Log( "当たっている" );
            Debug.Log( "当たっている場所:" + intersection );
        }
    }
}