WeiChen Chen
WeiChen Chen

Reputation: 1

Android sceneView 3D model HitResult

This is my first time trying 3D, I'm using SceneView

    <io.github.sceneview.SceneView
        android:id="@+id/sceneView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    private fun loadModel() {
        viewLifecycleOwner.lifecycleScope.launch {

            val modelFile = "test/test2.glb"
            val modelInstance = binding.sceneView.modelLoader.createModelInstance(modelFile)

            val modelNode = ModelNode(
                modelInstance = modelInstance,
            )

            binding.sceneView.addChildNode(modelNode)

            touchEvent()
        }
    }

I get the coordinate points through hitResult to generate a sphere

    private fun touchEvent() {
        val originalTouchEvent = binding.sceneView.onTouchEvent
        binding.sceneView.onTouchEvent = { motionEvent, hitResult ->
            if (isPointMode) {
                handleTouch(motionEvent, hitResult)
                true
            } else {
                originalTouchEvent?.invoke(motionEvent, hitResult) ?: false
            }
        }
    }

    private fun handleTouch(motionEvent: MotionEvent, hitResult: HitResult?) {
        when (motionEvent.action) {
            MotionEvent.ACTION_DOWN -> {
                hitResult?.let { hit ->
                    val hitPosition = Position(hit.point.x, hit.point.y, hit.point.z)
                    addSphere(roundedPosition)
                }
            }
        }
    }

But why is the sphere displayed in the bounding box, not on the 3D model?

I tried using the camera to generate rays on the model, but it doesn't work

            binding.sceneView.onTouchEvent = { motionEvent, hitResult ->
                if (motionEvent.action == MotionEvent.ACTION_DOWN) {
                    val ray = binding.sceneView.cameraNode.camera.viewToRay(Float2(motionEvent.x, motionEvent.y))
                    Logger.d(TAG, "Ray origin: ${ray.origin}, Ray direction: ${ray.direction}")
                    val screenHitResult = binding.sceneView.collisionSystem.hitTest(ray)
                    Logger.d(TAG,"size:${screenHitResult.size}")
                }
             .....
            }

I get the Logger- Ray origin: Float3(x=0.20247628, y=11.343173, z=-4.418243), Ray direction: Float3(x=485.11307, y=33983.13, z=-13357.227)

but size always 0

Upvotes: 0

Views: 32

Answers (0)

Related Questions