2D空间中求两圆的交点

 

 

出处:https://stackoverflow.com/questions/19916880/sphere-sphere-intersection-c-3d-coordinates-of-collision-points

 

修改(加入包含和不相交情况的判断):

复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CircleIntersect : MonoBehaviour
{
    public Transform circleA;
    public float radiusA = 1f;
    public Transform circleB;
    public float radiusB = 1f;


    public bool CalculateCircleIntersect(Vector3 c1p, Vector3 c2p, float c1r, float c2r, out Vector3 p0, out Vector3 p1)
    {
        //c1p = circle one position
        //c1r = circle one radius

        var P0 = c1p;
        var P1 = c2p;

        float d, a, h;
        p0 = Vector3.zero;
        p1 = Vector3.zero;

        d = Vector3.Distance(P0, P1);

        if (d > c1r + c2r) return false;
        if (Vector3.Distance(c2p, c1p) + c1r < c2r) return false;
        if (Vector3.Distance(c2p, c1p) + c2r < c1r) return false;

        a = (c1r * c1r - c2r * c2r + d * d) / (2 * d);

        h = Mathf.Sqrt(c1r * c1r - a * a);

        Vector3 P2 = (P1 - P0);
        P2 = (P2 * (a / d));
        P2 = (P2 + P0);

        float x3, y3, x4, y4 = 0;

        x3 = P2.x + h * (P1.y - P0.y) / d;
        y3 = P2.y - h * (P1.x - P0.x) / d;

        x4 = P2.x - h * (P1.y - P0.y) / d;
        y4 = P2.y + h * (P1.x - P0.x) / d; ;

        //out parameters for a line renderer
        p0 = new Vector3(x3, y3, 0);
        p1 = new Vector3(x4, y4, 0);

        return true;
    }

    void OnDrawGizmos()
    {
        if (circleA == null || circleB == null) return;

        var cacheColor = Gizmos.color;

        var p0 = default(Vector3);
        var p1 = default(Vector3);
        var isIntersect = CalculateCircleIntersect(circleA.position, circleB.position, radiusA, radiusB, out p0, out p1);

        if (isIntersect)
        {
            Gizmos.DrawWireSphere(p0, 0.1f);
            Gizmos.DrawWireSphere(p1, 0.1f);
            Gizmos.color = Color.red;
        }

        Gizmos.DrawWireSphere(circleA.position, radiusA);
        Gizmos.DrawWireSphere(circleB.position, radiusB);

        Gizmos.color = cacheColor;
    }
}
复制代码

 

posted @   HONT  阅读(712)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2016-05-04 Unity中实现List类型的自定义GUI(ReorderableList)
2016-05-04 [转]Unity: make your lists functional with ReorderableList
2013-05-04 二叉树的学习
点击右上角即可分享
微信分享提示
回到顶部