Angle of Face to Camera - three.js

故事扮演 提交于 2021-02-07 10:49:21

问题


If I create a geometry with just one face (triangle), like this:

[CoffeeScript syntax]

    geometry = new THREE.Geometry()
    geometry.vertices.push(new THREE.Vector3(0, 0, 0))
    geometry.vertices.push(new THREE.Vector3(0, 10, 0))
    geometry.vertices.push(new THREE.Vector3(0, 10, 10))
    geometry.faces.push(new THREE.Face3(0, 1, 2))
    mesh = new THREE.Mesh(geometry, material)
    mesh.position.x = 10
    @scene.add(mesh)

And I render the scene:

    @renderer.render(@scene, @camera)

How can I find out what the angle of the face is to the camera?

To clarify: If I the triangle is pointing right at the camera, so that width and hight are maximized, similar to this picture, then I would expect an angle of 0deg (or 180deg).

If the face is at a rotation to the camera where the triangle is just on line because I am looking at it exactly sideways, similar to this picture, I would expect the angle to be 90deg (or 270deg).


回答1:


I am going to assume that the direction that the camera is looking is not of importance to you, only its position is.

What you want to do is take the dot product of the face normal vector (the vector that points in the direction that the triangle is facing) and the vector that points in the direction from the triangle to the camera.

Here the n1 vector is the face normal:

var triangleNormal = triangleMesh.geometry.faces[0].normal

which has unit length. v is the vector pointing from the triangle to the camera

var dirToCamera = camera.position.clone().sub(triangleMesh.position);

and n2 is the just the normalized v:

dirToCamera.normalize();

Now, to get α, you take the dot product of n1 and n2

var angleValue = triangleNormal.dot(dirToCamera);

However ´angleValue´ is not expressed in degrees, its the cosine of the degrees. This value will be 1 when triangle is facing camera, 0 when at 90 degrees and -1 when facing the opposite direction.

If you want it in degrees, just do:

var angle = Math.acos(angleValue) * 180/Math.PI;

When more thing. When calculating n2 (dirToCamera), I used the triangle mesh position. If you are using a object with more than one face, you might want to calculate the center point of each triangle and use that instead of the mesh position.

Here is a codepen example



来源:https://stackoverflow.com/questions/36385478/angle-of-face-to-camera-three-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!