Realizar testes de hit no app Android NDK
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Faça um teste de hit para determinar o posicionamento correto de um objeto 3D na sua cena. O posicionamento correto garante que o conteúdo de RA seja renderizado no tamanho adequado (aparente).
Tipos de resultados de hit
Um teste de hit pode gerar quatro tipos diferentes de resultados de hit, conforme mostrado na tabela a seguir.
Tipo de resultado do hit |
Descrição |
Orientação |
Caso de uso |
Chamadas de método |
Profundidade (AR_TRACKABLE_DEPTH_POINT ) |
Usa informações de profundidade de toda a cena para determinar a profundidade e orientação corretas de um ponto.
|
Perpendicular à superfície 3D
|
colocar um objeto virtual em uma superfície arbitrária (não apenas no chão e nas paredes);
|
ArDepthMode precisa estar ativado para que isso funcione.
ArFrame_hitTest , verifique se há ArDepthPoint s na lista de retorno.
|
Avião (AR_TRACKABLE_PLANE ) |
Atinge superfícies horizontais e/ou verticais para determinar a profundidade e orientação corretas de um ponto
|
Perpendicular à superfície 3D
|
Coloque um objeto em um plano (solo ou parede) usando a geometria completa dele. Precisa da balança correta imediatamente. Substituto do teste de hit de profundidade
|
ArFrame_hitTest , verifique se há ArPlane s na lista de retornos.
|
Ponto de destaque (AR_TRACKABLE_POINT ) |
Baseia-se em recursos visuais ao redor do ponto em que o usuário toca para determinar a posição e orientação corretas de um ponto.
|
Perpendicular à superfície 3D
|
colocar um objeto em uma superfície arbitrária (não apenas no chão e nas paredes);
|
ArFrame_hitTest , verifique se há ArPoint s na lista de retornos.
|
Canal instantâneo (AR_TRACKABLE_INSTANT_PLACEMENT_POINT ) |
Usa o espaço na tela para posicionar conteúdo. Inicialmente, usa a profundidade estimada fornecida pelo app. Funciona instantaneamente, mas a pose e a profundidade real mudam quando o ARCore consegue determinar a geometria real da cena
|
+Y apontando para cima, oposto à gravidade
|
Coloque um objeto em um plano (solo ou parede) usando a geometria total dele. Nesse local, o posicionamento rápido é essencial, e a experiência pode tolerar a profundidade e a escala iniciais desconhecidas
|
ArFrame_hitTestInstantPlacement
|
Chame ArFrame_hitTest
para realizar um teste de hit.
ArHitResultList* hit_result_list = NULL;
ArHitResultList_create(ar_session, &hit_result_list);
CHECK(hit_result_list);
if (is_instant_placement_enabled) {
ArFrame_hitTestInstantPlacement(ar_session, ar_frame, x, y,
k_approximate_distance_meters,
hit_result_list);
} else {
ArFrame_hitTest(ar_session, ar_frame, x, y, hit_result_list);
}
Filtre os resultados de hits com base no tipo em que você tem interesse. Por exemplo, se você quiser se concentrar em ArPlane
s:
int32_t hit_result_list_size = 0;
ArHitResultList_getSize(ar_session, hit_result_list, &hit_result_list_size);
// Returned hit-test results are sorted by increasing distance from the camera
// or virtual ray's origin. The first hit result is often the most relevant
// when responding to user input.
ArHitResult* ar_hit_result = NULL;
for (int32_t i = 0; i < hit_result_list_size; ++i) {
ArHitResult* ar_hit = NULL;
ArHitResult_create(ar_session, &ar_hit);
ArHitResultList_getItem(ar_session, hit_result_list, i, ar_hit);
if (ar_hit == NULL) {
LOGE("No item was hit.");
return;
}
ArTrackable* ar_trackable = NULL;
ArHitResult_acquireTrackable(ar_session, ar_hit, &ar_trackable);
ArTrackableType ar_trackable_type = AR_TRACKABLE_NOT_VALID;
ArTrackable_getType(ar_session, ar_trackable, &ar_trackable_type);
// Creates an anchor if a plane was hit.
if (ar_trackable_type == AR_TRACKABLE_PLANE) {
// Do something with this hit result. For example, create an anchor at
// this point of interest.
ArAnchor* anchor = NULL;
ArHitResult_acquireNewAnchor(ar_session, ar_hit, &anchor);
// TODO: Use this anchor in your AR experience.
ArAnchor_release(anchor);
ArHitResult_destroy(ar_hit);
ArTrackable_release(ar_trackable);
break;
}
ArHitResult_destroy(ar_hit);
ArTrackable_release(ar_trackable);
}
ArHitResultList_destroy(hit_result_list);
Realizar um teste de hit usando um raio e uma direção arbitrários
Os testes de hit costumam ser tratados como raios da câmera do dispositivo ou da câmera, mas é possível usar ArFrame_hitTestRay
para conduzir um teste de hit usando um raio arbitrário em coordenadas de espaço mundial em vez de um ponto de espaço na tela.
Anexar uma âncora a um HitResult
Quando você tiver um resultado de hit, poderá usar a posição dele como entrada para colocar conteúdo de RA na sua cena. Use ArHitResult_acquireNewAnchor
para criar uma nova Âncora no local do hit.
O que vem em seguida?
- Confira o app de exemplo
hello_ar_c
(link em inglês) no GitHub.
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-07-26 UTC.
[null,null,["Última atualização 2025-07-26 UTC."],[[["\u003cp\u003eUse hit-tests to accurately place 3D objects in your AR scene by determining their correct position and orientation in the real world.\u003c/p\u003e\n"],["\u003cp\u003eHit-tests offer four types of results: Depth, Plane, Feature Point, and Instant Placement, each suited for different placement scenarios and surface types.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eArFrame_hitTest\u003c/code\u003e and \u003ccode\u003eArFrame_hitTestInstantPlacement\u003c/code\u003e are the primary methods used to perform hit-tests, with the former focusing on precision and the latter on speed.\u003c/p\u003e\n"],["\u003cp\u003eOnce a hit-test is performed, filter the results based on your desired trackable type (e.g., planes) and create an anchor to attach your AR content to the hit location.\u003c/p\u003e\n"],["\u003cp\u003eAnchors are created from successful hit-tests using \u003ccode\u003eArHitResult_acquireNewAnchor\u003c/code\u003e, allowing virtual objects to remain persistently placed in the real world.\u003c/p\u003e\n"]]],["Hit-tests determine 3D object placement in AR scenes, ensuring correct size. Four result types exist: Depth (for arbitrary surfaces), Plane (for floors/walls), Feature Point (for user-tapped surfaces), and Instant Placement (for rapid, initially estimated placement). Use `ArFrame_hitTest` or `ArFrame_hitTestInstantPlacement` to perform hit tests and filter results based on `ArTrackableType`. `ArFrame_hitTestRay` enables tests with arbitrary rays. `ArHitResult_acquireNewAnchor` creates an Anchor at the hit location for AR content placement.\n"],null,["# Perform hit-tests in your Android NDK app\n\nPerform a [hit-test](/ar/develop/hit-test) to determine the correct placement of a 3D object in your scene. Correct placement ensures that the AR content is rendered at the appropriate (apparent) size.\n\nHit result types\n----------------\n\nA hit-test can yield four different types of hit results, as shown by the following table.\n\n| Hit result type | Description | Orientation | Use case | Method calls |\n|---------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Depth ([`AR_TRACKABLE_DEPTH_POINT`](/ar/reference/c/group/ar-trackable#ar_trackable_depth_point)) | Uses depth information from the entire scene to determine a point's correct depth and orientation | Perpendicular to the 3D surface | Place a virtual object on an arbitrary surface (not just on floors and walls) | **[`ArDepthMode`](/ar/reference/c/group/ar-config#ardepthmode) must be enabled for this to work.** [`ArFrame_hitTest`](/ar/reference/c/group/ar-frame#arframe_hittest), check for [`ArDepthPoint`](/ar/reference/c/group/ar-depth-point#ardepthpoint)s in the return list |\n| Plane ([`AR_TRACKABLE_PLANE`](/ar/reference/c/group/ar-trackable#ar_trackable_plane)) | Hits horizontal and/or vertical surfaces to determine a point's correct depth and orientation | Perpendicular to the 3D surface | Place an object on a plane (floor or wall) using the plane's full geometry. Need correct scale immediately. Fallback for the Depth hit-test | [`ArFrame_hitTest`](/ar/reference/c/group/ar-frame#arframe_hittest), check for [`ArPlane`](/ar/reference/c/group/ar-plane)s in the return list |\n| Feature point ([`AR_TRACKABLE_POINT`](/ar/reference/c/group/ar-trackable#ar_trackable_point)) | Relies on visual features around the point of a user tap to determine a point's correct position and orientation | Perpendicular to the 3D surface | Place an object on an arbitrary surface (not just on floors and walls) | [`ArFrame_hitTest`](/ar/reference/c/group/ar-frame#arframe_hittest), check for [`ArPoint`](/ar/reference/c/group/ar-point)s in the return list |\n| Instant Placement ([`AR_TRACKABLE_INSTANT_PLACEMENT_POINT`](/ar/reference/c/group/ar-trackable#ar_trackable_instant_placement_point)) | Uses screen space to place content. Initially uses estimated depth provided by the app. Works instantly, but pose and actual depth will change once ARCore is able to determine actual scene geometry | +Y pointing up, opposite to gravity | Place an object on a plane (floor or wall) using the plane's full geometry where fast placement is critical, and the experience can tolerate unknown initial depth and scale | [`ArFrame_hitTestInstantPlacement`](/ar/reference/c/group/ar-frame#arframe_hittestinstantplacement) |\n\nPerform a standard hit-test\n---------------------------\n\nCall [`ArFrame_hitTest`](/ar/reference/c/group/ar-frame#arframe_hittest) to perform a hit test. \n\n```c\nArHitResultList* hit_result_list = NULL;\nArHitResultList_create(ar_session, &hit_result_list);\nCHECK(hit_result_list);\nif (is_instant_placement_enabled) {\n ArFrame_hitTestInstantPlacement(ar_session, ar_frame, x, y,\n k_approximate_distance_meters,\n hit_result_list);\n} else {\n ArFrame_hitTest(ar_session, ar_frame, x, y, hit_result_list);\n}\n```\n\nFilter hit results based on the type you're interested in. For example, if you'd like to focus on `ArPlane`s: \n\n```c\nint32_t hit_result_list_size = 0;\nArHitResultList_getSize(ar_session, hit_result_list, &hit_result_list_size);\n\n// Returned hit-test results are sorted by increasing distance from the camera\n// or virtual ray's origin. The first hit result is often the most relevant\n// when responding to user input.\nArHitResult* ar_hit_result = NULL;\nfor (int32_t i = 0; i \u003c hit_result_list_size; ++i) {\n ArHitResult* ar_hit = NULL;\n ArHitResult_create(ar_session, &ar_hit);\n ArHitResultList_getItem(ar_session, hit_result_list, i, ar_hit);\n\n if (ar_hit == NULL) {\n LOGE(\"No item was hit.\");\n return;\n }\n\n ArTrackable* ar_trackable = NULL;\n ArHitResult_acquireTrackable(ar_session, ar_hit, &ar_trackable);\n ArTrackableType ar_trackable_type = AR_TRACKABLE_NOT_VALID;\n ArTrackable_getType(ar_session, ar_trackable, &ar_trackable_type);\n // Creates an anchor if a plane was hit.\n if (ar_trackable_type == AR_TRACKABLE_PLANE) {\n // Do something with this hit result. For example, create an anchor at\n // this point of interest.\n ArAnchor* anchor = NULL;\n ArHitResult_acquireNewAnchor(ar_session, ar_hit, &anchor);\n\n // TODO: Use this anchor in your AR experience.\n\n ArAnchor_release(anchor);\n ArHitResult_destroy(ar_hit);\n ArTrackable_release(ar_trackable);\n break;\n }\n ArHitResult_destroy(ar_hit);\n ArTrackable_release(ar_trackable);\n}\nArHitResultList_destroy(hit_result_list);\n```\n\nConduct a hit-test using an arbitrary ray and direction\n-------------------------------------------------------\n\nHit-tests are typically treated as rays from the device or device camera, but you can use [`ArFrame_hitTestRay`](/ar/reference/c/group/ar-frame#arframe_hittestray) to conduct a hit-test using an arbitrary ray in world space coordinates instead of a screen-space point.\n\nAttach an Anchor to a HitResult\n-------------------------------\n\nOnce you have a hit result, you can use its pose as input to [place AR content](/ar/develop/anchors) in your scene. Use [`ArHitResult_acquireNewAnchor`](/ar/reference/c/group/ar-hit-result#arhitresult_acquirenewanchor) to create a new [Anchor](/ar/develop/anchors) at the hit location.\n\nWhat's next\n-----------\n\n- Check out the [`hello_ar_c`](https://github.com/google-ar/arcore-android-sdk/tree/master/samples/hello_ar_c) sample app on GitHub."]]