- Home /
Not Able to Position Sprite By Pixels
Hi,
So I am making my first game in Unity 2D (I have experience with Unity 3D), and I run into a problem immediately. When I try to set the position of a sprite using transform.position = new Vector2(100, 100); //or whatever, instead of putting it in that pixel position, it places it on the grid square 100 grid squares from the center. I would like to know how to position a sprite based on pixels, not grid squares.
Any help would be greatly appreciated, thanks!
Answer by theInsomniacGameMaker · Sep 24, 2018 at 07:37 PM
When working in any game there are two spaces.
World Space
Screen Space
Since you are experienced in 3D I will try to explain it in those terms.
The 3D model that you place is in World Space and if you have used a Canvas or UI that is in Screen Space.
Here when you are assigning the position of the sprite you are assigning it in World Space, just that you don't have a Z axis.
And you want to align it in Screen Space. So there is a way.
You want to use ScreenToWorldPoint. And pass the position you need to, and assign the result of that function to the transform.position.
You should also know something, the bottom left is the position (0,0) and the right-top is (pixelWidth, pixelHeight). Read about this function here.
If you any other question let me know!
Thanks for the advice, this works. However, it seems a little bit tedious to do this every time I want to position something. Is there a way you know of that allows me to set that to be the default or something? I could make a method that does this, but again I would have to implement it into every script that did this. Thanks for the help though!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Ball Bouncing 1 Answer
How to do you import Spriter animations into Unity? 1 Answer