0
2

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.

2D線分計算Class

Last updated at Posted at 2022-02-15

線分と線分の交差判定や交差点、線分と点との最短距離、外積と法線を求める等の2Dでよく使う処理をまとめたClass

ClassLine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//線分class
public class ClassLine
{
    public Vector2 p1;//開始点
    public Vector2 p2;//終了点

    //線分コンストラクタ
    public ClassLine(Vector2 p1, Vector2 p2)
    {
        this.p1 = p1;
        this.p2 = p2;
    }
    //複製
    public ClassLine Clone()
    {
        return new ClassLine(p1, p2);
    }
    //ベクトル
    public Vector2 v
    {
        get { return p2 - p1; }
    }
    //2点間の距離
    public float distance
    {
        get { return Vector2.Distance(p1, p2); }
    }
    //外積
    public float cross(Vector2 p1, Vector2 p2)
    {
        return p1.x * p2.y - p2.x * p1.y;
    }
    //平行
    public bool isParallel(ClassLine line)
    {
        return cross(v, line.v) <= Vector2.kEpsilon;
    }
    //法線
    public Vector2 normal
    {
        get
        {
            return Vector2.Perpendicular(v);
        }
    }
    //最近点
    public Vector2 nearestPoint(Vector2 point)
    {
        Vector2 v1 = point - p1;
        float dot = Vector3.Dot(v, v1);

        Vector2 p = p1 + v * dot / v.sqrMagnitude;
        if (Vector2.Dot(p - p1, v) < 0) { p = p1; }
        else if (Vector2.Distance(p1, p) > distance) { p = p2; }

        return p;
    }
    //線分との交差判定
    public bool isCross(ClassLine line)
    {
        Vector2 v1 = p1 - line.p1;
        Vector2 v2 = p2 - line.p1;
        Vector2 v3 = line.p1 - p1;
        Vector2 v4 = line.p2 - p1;
        return cross(line.v, v1) * cross(line.v, v2) < 0 && cross(v, v3) * cross(v, v4) < 0;
    }
    //線分との交差点
    public Vector2 crossPoint(ClassLine line)
    {
        Vector2 v1 = line.p1 - p1;
        float nume = cross(v1, line.v);
        float deno = cross(v, line.v);
        float t = 0;
        if (deno != 0)
        {
            t = nume / deno;
        }
        return p1 + v * t;
    }
    //点との最短距離
    public float distanceFromPoint(Vector2 point)
    {
        return Vector2.Distance(nearestPoint(point), point);
    }
}

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?