- Home /
Converting world coordinates to screen coordinates
Currently I'm working on an particle system to display over a GUI.Label I have when a new best score has been achieved. The labels are created using this snippet of code "GUI.Label (new Rect(95, 160, 175, 40), "" + bestScore, style);"
I made my particle system object a prefab, so what I would like to do is Instantiate this in my script so that the particle object is directly over my new best score label. Figured it would be much easier doing this since I have multiple scenes but I'm just not familiar enough in Unity3d right now. I'm mainly used to working in pixels only.
From what I've been reading many say that I should be using Camera.WorldToScreenPoint?
Any help/nudge in the right direction would be great.
TiA,
T
Answer by robertbu · Apr 28, 2014 at 06:08 PM
The only tricky part of this problem is that GUI uses a GUI coordinate system that starts in the upper left of the screen, where Screen coordinates start in the lower left of the screen. First pull out the Rect into a variable at the top of your C# class:
private Rect bestScoreRect = new Rect(95, 160, 175, 40);
Then the code to create a world position would be:
Vector3 pos = bestScoreRect.center;
pos.y += bestScoreRect.height / 2.0; // Position at top of rect
pos.y = Screen.height - pos.y; // Convert from GUI to Screen
pos.z = someDist; // Distance in front of the camera
pos = Camera.main.ScreenToWorldPoint(pos);
'someDist' is the distance in front of the camera in world space to place the object. And as a final note, your particle system prefab lives in World space, so what the code here does is convert the GUI/Screen coordinate to world space...the opposite of your title.
Thanks for the quick reply. So basically I instantiate my particleSystem object and pass in the pos.x, pos.y, pos.z as Vector3?
You can use 'pos' in the Instantiate():
Instantiate(prefabPS, pos, Quaternion.identity);
Note you may need to make changes to the ParticleSystem settins, or perhaps raise the 'y' position up some more on line 2 of the code fragment. You'll have to try it and play to get the look you want.
I appreciate your time and help along with the speedy responses. Works just fine :)
Line 2 makes no sense. Vector3 doesn't have a height property. Did you mean bestScoreRect.height? $$anonymous$$ust have.
@tpainton - you are right. Fixed. Thanks for bringing it to my attention.