zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    web print
    datediff
    Typical AJAX
    sql中构建sql语句,再exec这条SQL语句
    ASP.NET中将数据输出到WORD、EXCEL、TXT、HTM
    sql中添加单引号
    sql语句批处理
    日期分组
    异步线程
    电脑内存大有什么好处?
  • 原文地址:https://www.cnblogs.com/hont/p/8991727.html
Copyright © 2011-2022 走看看