球击中矩形时如何确定正常?

时间:2014-01-26 01:46:09

标签: android collision

我定义了这个常量,但我不确定如何找到正常的索引。

public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int UP = 2;
public static final int DOWN = 3;

public float[] normals = {-1, 0, 1, 0, 0, 1, 0, -1};

public float4 getNormal(int index)
{
    return new float4(normals[index * 2], normals[index * 2 + 1], 0);
}

public static int normal(float x, float y, RectF rect)
{
    // need to find the normal index here
    return normal_index;
}

1 个答案:

答案 0 :(得分:0)

我认为这应该适用于内部和外部点(半径中心):

public static int normal_index(float x, float y, RectF rect)
{
    float cx = rect.left + rect.width() * 0.5f;
    float cy = rect.top + rect.height() * 0.5f;

    boolean a = x - rect.left < rect.bottom - y;
    boolean b = x - rect.left < y - rect.top;
    boolean c = x - rect.right < y - rect.bottom;
    boolean d = x - rect.right < rect.top - y;

    if (a && b && x < cx ) return LEFT;     
    else if (!c && !d && x >= cx ) return RIGHT;        
    else if (!a && c && y >= cy ) return DOWN;      
    else if (!b && d && y < cy ) return UP;

    return -1;
}

问题似乎与此问题有关Given a point inside a rectangle, determine the side that's closest to the point

对于a,b,c,d行,我有类似的图片:

pic http://oi39.tinypic.com/23hrbtk.jpg