- Home /
Keep sprites in the same position relative to screen resolution.
I used to use OnGUI for scaling and position my textures. One of them is 120x120 pixels and has to be 15 pixels from the top and 15 pixels from the left on the screen. I wrote the scaling and positioning scripts for it and it all worked fine. Now I moved to using sprites. I'm using a perspective camera, field of view is 60, sprite pixels to units - 100. I made a line of code which scales the sprite and keeps it the same size relative to the screen resolution. Now - I do not know how to keep their position - if it is 0, 0, 0 - it will always be in the center - all is good. But, as I said, it has to be 15 pixels from the top left side of the screen. How to do it so my sprites would always remain in the same place?
Answer by robertbu · Aug 18, 2014 at 08:35 PM
For a perspective camera, you have to define a distance from the camera to position the sprite. Let's say you pick 10 units. Next select your sprite texture and in the Inspector, set your 'Pivot' to 'Top left'. Then to place the object, you can do:
var pos = Vector3(15, Screen.height - 15, 10);
transform.position = Camera.main.ScreenToWorldPoint(pos);
If your camera does not move or if the sprite is a child of the camera, then you can do this in Start(). If things move, you need to do it in Update().
Answer by Vitor_r · Aug 18, 2014 at 08:39 PM
You will need to have a script on the GameObject and in Awake (or Start) function of this script change the position of the GameObject relative to the Screen.width and Screen.height