PV3D 2D->3D , 3D->2D
Posted: July 16th, 2009 | Author: Tiago Bilou | Filed under: 3D, Actionscript3, Papervision3d | 4 Comments »This week I finally had a project that involved 3D (about time too).
Since it involved interacting with 3D models, using Flash 10 was out of the question. So I opted to go with papervision, instead of away3D or alternativa3D, since this was the engine we where more accustomed to.
Sometime along the development of the application I came across the need to convert 3D coordinates into 2D screen coordinates and also the opposite. It's nothing new and it's already implemented in papervision, but since it took me a little while to find it, I decided to share it.
Getting the 2D Screen coordinates from a DisplayObject3D
Since papervision 2.0 that every DisplayObject3D has a property called "screen", that will return the coordinate of the object on screen. Whenever I tried to access the screen property the number3D I got back was always (0,0,0). Probably because it's an expensive operation and it's something you only need sporadically, papervision will not calculate this automatically. You need to ask papervision yourself to calculate this coordinates. To do so, just use the "calculateScreenCoords" of the do3d
myDisplayObject3D.calculateScreenCoords(camera)
Now when you try to access the "screen" property you will get the number3D with the screen coordinates for your DisplayObject3D.
Getting the 3D coordinates from a 2D point (x,y)
For this one I found a great post by zupko that tells you exactly what you need to do.
In a nutshell, you need to take your 2D coordinates (x,y) and convert them into a direction vector. Having the vector and the camera position you can create a ray (line) that will go from the camera into infinity. Next you need to specify the Z, or in another words, where do you want to stop on that line. Zupko uses a 3D plane to do that using the "getIntersectionLineNumbers"
Just remember papervision's 3D Zero (0,0,0) is at the center of the screen and not on the upper left corner like the 2D Zero (0,0)