如何解决圆碰撞问题

时间:2014-05-11 19:05:39

标签: c# geometry collision

当我发现两个圆圈之间的碰撞时,我可以做什么,以防止两个圆圈相互穿过?

public class CircleVsCircle
{
    public Vector2 position { get; set; } //top left corner
    public float CenterX;
    public float CenterY;
    public int Width { get; set; }
    public int Height { get; set; }
}

public void CircleVsCircle(CircleBody body1, CircleBody body2)
{
    float radius = (body1.Radius + body2.Radius);
    radius *=radius;
    float distance = ((body1.CenterX - body2.CenterX) *
        (body1.CenterX - body2.CenterX)) + 
        ((body1.CenterY - body2.CenterY) * 
        (body1.CenterY - body2.CenterY));

    if(radius > distance)
    {
        //solve the collision here
    }
}

2 个答案:

答案 0 :(得分:0)

我假设你的CircleBody类已经实现了像 x 位置 y 位置

这可能是circle-circle collision

的公告
public void CircleVsCircle(CircleBody body1, CircleBody body2)
{
    float radius = (body1.Radius + body2.Radius);
    radius *=radius;
    float distance = ((body1.CenterX - body2.CenterX) *
        (body1.CenterX - body2.CenterX)) + 
        ((body1.CenterY - body2.CenterY) * 
        (body1.CenterY - body2.CenterY));

    if(radius > distance)
    {
        double deltaXSquared = body1.x - body2.x; // calc. delta X
        deltaXSquared *= deltaXSquared; // square delta X
        double deltaYSquared = body1.y - body2.y; // calc. delta Y
        deltaYSquared *= deltaYSquared; // square delta Y

        // Calculate the sum of the radix, then square it
        double sumRadiiSquared = body1.radius + body2.radius; 
        sumRadiiSquared *= sumRadiiSquared;

        if(deltaXSquared + deltaYSquared <= sumRadiiSquared){
          // body1 and body2 are touching
        }
    }
}

答案 1 :(得分:0)

这是我写的一篇关于圆碰撞的课程:link

这是处理两个圈子碰撞的代码:

public static boolean intersects(Circle circle1, Circle circle2) {

        // Use Pythagorean theorem
        int a = circle1.getCenterX() - circle2.getCenterX();
        int b = circle1.getCenterY() - circle2.getCenterY();
        float c = (float) FloatMath.sqrt((float) (Math.pow(a, 2) + Math.pow(b, 2)));

        if((circle1.getRadius() + circle2.getRadius()) == c || (circle1.getRadius() + circle2.getRadius()) > c) {
            return true;

        }
        else {
            return false;

        }

    }

这基本上取两个圆的两个中心之间的距离(使用毕达哥拉斯),并确保它小于圆的两个半径加在一起。如果它少了,那么我们就知道发生了碰撞。

相关问题