提问者:小点点

如何解决圆碰撞


当我发现两个圆之间的碰撞时,我必须做什么才能阻止两个圆互相穿过?

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个答案

匿名用户

我假设你的CircleBody类已经实现了像x位置和y位置这样的属性

这可能是圆-圆碰撞的翻版

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
        }
    }
}

匿名用户

这是我写的一个处理圆碰撞的类:链接

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

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;

        }

    }

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