Unity is so difficult compared to delphi. In delphi you can just say:
Rectangle1.Position.Y := 0;
Rectangle1.Position.X := screen.Width - Rectangle1.Width;
This will just change the position of the Rectangle to the top right corner of the screen. But in Unity there's so much to learn just to do this and I don't know where I start. Can someone please simplify this to me? I just want create a object at the top right corner of the screen, both in smartphones and pcs.
I'm using Unity2D
EDIT: This is the Inspector of the object that I want to create:
And this is the code that I use to create Objects on the screen:
Instantiate(objectName, new Vector3(0, 0, 0), Quaternion.identity);
EDIT to be more clear:
The screen coordinate of the camera is not the same as the world coordinate (one has 2 dimensions & the other has 3. One uses pixels & the other Unity units).
I would use Camera.ScreenToWorldPoint.
Qouting the docs :
Camera.ScreenToWorldPoint(position: Vector3) Transforms position from screen space into world space.
Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.
So to put your Rectangle on the corner in a similar way to what you described (with pseudocode C# mix):
Vector3 p = camera.ScreenToWorldPoint(new Vector3(0, Screen.height, HowFarFromCamera));
Rectangle1.position = new Vector3(p.x + Rectangle1.Width/2,p.y - Rectangle1.Height/2,p.z);
Point p is the corner in world coordinate (which is the important thing). I shifted by Width/2 and Height/2 assuming that your rectangle's pivot is in the middle.
Note: You can use Bounds.size to get the width or height (a struct available for both Renderer & SpriteRenderer)
Another suggestion I'd give you since you seem to be working exclusively with 2D (looking at your other posts) is to look for Unity UI system (which was released in 4.6 : many people refer to it as UI 4.6) :
The idea is you can anchor your objects inside a Canvas : in your situation you'll only have to anchor an Image to the desired corner and then to offset it by half its width/height (you can also set the object pivot point to the right corner and anchor it to the matching corner without having to offset it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With