If you are creating a game that provides a 2D interface on top of a 3D world, for instance, as shown in the Creating a 2D overlay recipe, you might want to know how the 3D coordinates map to your 2D overlay. If you know the 2D coordinates, you can add all kinds of visual effects to the 2D overlay, such as tracking the code or letting the 2D overlay interact with the objects in the 3D scene.
You don't need to perform any steps to get ready for this recipe. In this recipe, we can use the THREE.Projector
object available in Three.js to determine the correct coordinates. You can view the result from this recipe in action by opening 03.07-convert-world-coordintate-to-screen-coordinates.html
in your browser as shown in the following screenshot:
The box appears at random positions when you open this example. When you click on the calculateScreenCoordinate button in the menu in the top-right section, the x and y coordinates of the center of the box will be shown.
To convert world coordinates to screen coordinates, we use a couple of internal Three.js objects:
THREE.Projector
:var projector = new THREE.Projector();
var vector = new THREE.Vector3(); projector.projectVector( vector.setFromMatrixPosition( object.matrixWorld ), camera );
The vector
variable will now contain the position of the object as it is seen by the camera
object.
var width = window.innerWidth; var height = window.innerHeight; var widthHalf = width / 2; var heightHalf = height / 2; vector.x = ( vector.x * widthHalf ) + widthHalf; vector.y = - ( vector.y * heightHalf ) + heightHalf;
At this point, the vector
variable will contain the screen coordinates of the center of object
. You can now use these coordinates with standard JavaScript, HTML, and CSS to add effects.
In this recipe, we use the same effect that Three.js uses to render the scene. When you render a scene, the objects are projected onto a camera, which determines what area needs to be rendered and where the objects appear. With the projector class, we can perform this projection for a single vector. The result is the position of this vector in two dimensions based on the used camera.
18.117.103.5