- Home /
Drawing Objects Using Window Coords
Could someone explain to me how I would go about drawing a sprite at a location in the window. For example, if I wanted to draw it at the bottom left corner (or 0,0) how would I be able to this?
To be a bit more specific here is what I have so far:
Vector3 screenPoint = new Vector3(100,0,0);
Vector3 worldPos = Camera.main.ScreenToWorldPoint( screenPoint );
Quaternion ZeroRotation = new Quaternion(0,0,0,0);
GameObject tempTile = (GameObject)Instantiate(Resources.Load("Tile"),worldPos,ZeroRotation);
However, rather than drawing the tile at 100,0,0 in my 1920x1080 screen it draws it closer to 350,0,0.
After running this script in the Editor, what are the coordinates of the:
Sprite
Recursive Parents of the Sprite
And, have it debug all of the calculations in your script and post them.
This will help us pinpoint what is going wrong.
Also, try instantiating the sprite and then positioning it.
Answer by ThatsAMorais · Dec 03, 2013 at 06:18 AM
You're looking for "Screen", I think. In other words...
Vector3 screenPoint = new Vector3(Screen.width,Screen.height,0);
Quaternion ZeroRotation = new Quaternion(0,0,0,0);
GameObject tempTile = (GameObject)Instantiate(Resources.Load("Tile"),screenPoint,ZeroRotation);
This code will place the sprite at the bottom-left.
What this ends up doing is making a tile very far to the right way off the screen. In the code snippet I added I'm using ScreenToWorldPoint() which seems to be what I need but it's not giving me my expected results.
Answer by robertbu · Dec 03, 2013 at 06:24 AM
Your problem is the 'z' parameter you set for your initial screenPoint. This value needs to be set to distance in front of the camera. A value of '0' will place the object at the camera position regardless of the 'x' and 'y' values. So to set it 10 units in front of the camera:
Vector3 screenPoint = new Vector3(100,0,10);
Vector3 worldPos = Camera.main.ScreenToWorldPoint( screenPoint );
Note there is a shortcut for zero rotation called 'Quaternion.identity', so you don't need to do your 'zeroRotation' code above just do:
GameObject tempTile = Instantiate(Resources.Load("Tile"), worldPos, Quaternion.identity) as GameObject;
$$anonymous$$y camera is placed at -10 so a value of 0 in the z axis for my object should be fine.
The 'z' parameter is not the position in world space, but the distance in front of the camera. So if your camera is at -10, and you want to deter$$anonymous$$e a screen position at 'z' = 0, you need to enter '10' (i.e. 0 -(-10)) for the 'z' parameter. If your camera was at -20 and the position you were looking for was +10, then you would enter '30' for the 'z' parameter.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123305im_/https://answers.unity.com/themes/thub/images/avi.jpg)