- Home /
Converting Pixels to Units and Position Prefab
Hi,
I am working on a game that adds prefabs at runtime. Each prefab is added by getting information from a remote JSON file that contains the position & scale data for the prefab. I want to add the prefabs and position them correctly on a plane. So far I am able to read the JSON file and add the prefab, the problem is that the JSON position and scale data is in pixels. What would be the best way to normalize the data so that I can position and scale them correctly?
Any suggestions are really appreciated!
You can't convert pixels to units without a set conversion factor. Imagine an picture in 3d space. The image is 300x300 pixels. How many units tall is it? You can't possibly answer that
What kind of a prefab are we taking about...2D or 3D? Are you trying to match some texture pixel size to screen pixels, or are you just looking for some arbitrary mapping? Not that it makes much difference, but are you using an Orthographic or Perspective camera?
The prefab is 2D. I understand what @Benprodutions is saying however I know that the plane should be 1024x512 pixels, I tried creating an empty GameObject with those dimensions, adding the prefabs then scaling the GameObject to the size of the plane but that didnt work either
"The plane should be 1024x512 pixels", is that in screen space? If you convert 1 pixel of screen space to world space you get your conversion factor. A plane can't actually be 1024x512 pixels in world space, it's literally impossible in a 3d engine :)
sorry i dont think I explained myself correctly. Basically I have an external application where users add "assets" to a workspace that is 1024x512. In unity the workspace is represented by a plane, and the assets are the prefabs. Because the external application is web-based all the data is pixels. How do I "convert 1 pixel of screen space to world space" as you suggested?
Answer by robhuhn · Aug 02, 2013 at 09:07 AM
if you just need the relation of the plane and the assets (e.g. assetposition 512, 256 would be center of the plane) then you need to devide the asset position by the half of the total with 1024, 512 and subtract 1 to get a ratio from -1 to 1 (0 would be the center). Then multiply the ratio by the half plane bounds size in meters:
Vector3 assetPosition = new Vector3(1024, 256, 10);
assetPosition.x = (assetPosition.x / (imageSize.x * .5f) - 1) * plane.renderer.bounds.size.x * .5f; //plane.renderer.bounds x y z depends on plane rotation
assetPosition.y = (assetPosition.y / (imageSize.y * .5f) - 1) * plane.renderer.bounds.size.y * .5f;