我正在使用带有Android,Java代码的OpenGLES 2.0进行3D对象渲染。如何使用以下代码在近处和远处位置识别3D对象内部或外部3D对象?
public static PointF screenToWorld(float[] viewMatrix,
float[] projMatrix, float screenX, float screenY) {
float[] nearPos = unProject(viewMatrix, projMatrix, screenX, screenY, 0);
float[] farPos = unProject(viewMatrix, projMatrix, screenX, screenY, 1);
Log.d(LOGTAG,"nearPos ->"+nearPos.length+" "+nearPos);
Log.d(LOGTAG,"farPos ->"+farPos.length+" "+farPos);
// The click occurred in somewhere on the line between the two points
// nearPos and farPos. We want to find
// where that line intersects the plane at z=0
float distance = nearPos[2] / (nearPos[2] - farPos[2]); // Distance between nearPos and z=0
float x = nearPos[0] + (farPos[0] - nearPos[0]) * distance;
float y = nearPos[1] + (farPos[1] - nearPos[0]) * distance;
return new PointF(x, y);
}
private static float[] unProject(float[] viewMatrix,
float[] projMatrix, float screenX, float screenY, float depth) {
float[] position = {0, 0, 0, 0};
int[] viewPort = {0, 0, 1, 1};
GLU.gluUnProject(screenX, screenY, depth, viewMatrix, 0, projMatrix, 0,
viewPort, 0, position, 0);
position[0] /= position[3];
position[1] /= position[3];
position[2] /= position[3];
position[3] = 1;
return position;
}
答案 0 :(得分:4)
如何识别3D对象内部或3D对象外部的点击?
您必须验证是否点击了对象的任何基元。
近平面上的点和远平面上的点定义了穿过世界的光线:
float[] nearPos = unProject(viewMatrix, projMatrix, screenX, screenY, 0);
float[] farPos = unProject(viewMatrix, projMatrix, screenX, screenY, 1);
伪代码:
R0 = nearPos
D = normalize(farPos - nearPos)
要找到被光线击中的曲面,必须计算每个曲面(基元)与光线的交点和光线起点的距离。具有最低距离(在光线方向上)的表面被击中。
要查找光线与三角形基元的交点距离,必须执行以下步骤:
找到交叉点和交叉点距离:
平面由范数向量(NV
)和平面上的点(P0
)定义。如果3点PA
,PB
和PC
给出三角形,则可以按如下方式计算平面:
P0 = PA
NV = normalize( cross( PB-PA, PC-PA ) )
通过代入光线的方程来计算光线与平面的交点
P_isect = dist * D + R0
进入飞机dot( P_isect - P0, NV ) == 0
的等式。{
它如下:
P_isect = R0 + D * dist_isect
dist_isect = dot( P0 - R0, NV ) / dot( D, NV )
测试交点是否在光线方向:
如果`dist_isect大于或等于0.0,则交点位于光线方向。
测试交点是否在三角形中或在三角形上
要找出,如果一个点位于三角形内部,则必须进行测试,如果从角点到交叉点的直线位于连接到角点的连接点之间:
bool PointInOrOn( P1, P2, A, B )
{
CP1 = cross( B - A, P1 - A )
CP2 = cross( B - A, P2 - A )
return dot( CP1, CP2 ) >= 0
}
bool PointInOrOnTriangle( P, A, B, C )
{
return PointInOrOn( P, A, B, C ) &&
PointInOrOn( P, B, C, A ) &&
PointInOrOn( P, C, A, B )
}
另见:Is it possble get which surface of cube will be click in OpenGL?