Any game with a rocky mountainous lunar terrain and “ROCKET DEMO” on it is my kinda game!!
Generally don’t manipulate UI Transforms in code, unless the positions are derivative of OTHER UI Transforms already in the scene, such as anchors placed at the corners of your screen.
The reason is that it takes like 17 lines of code just to move anchors to the corners of a RectTransform, and that should be about the simplest thing possible, and it’s not.
I usually make a public RectTransform LowerLeftCorner
and UpperRightCorner
property and drag hard-anchored stuff into those, then use the fraction X and Y (also known as “Viewport” in Unity camera speak) to move the UI element to a fraction between those, like so:
// use Camera.WorldToViewport to get these fractional input values
public void SetViewportPosition( float xfraction, float yfraction)
{
xfraction = xfraction + 0.5f;
yfraction = yfraction + 0.5f;
// maybe use LerpUnclamped() if you prefer...
float x = Mathf.Lerp( LowerLeftCorner.position.x, UpperRightCorner.position.x, xfraction);
float y = Mathf.Lerp( LowerLeftCorner.position.y, UpperRightCorner.position.y, yfraction);
transform.position = new Vector3( x, y);
}
Regardless, you’ll want to keep this stuff firmly in mind too:
Here are the official docs on how to make your UI handle various resolutions and aspect ratios cleanly:
Here are some notes on UI Anchoring, Scaling, CanvasScaler, etc:
Usually you need to choose a suitable ScaleMode and MatchMode in the Canvas Scaler and stick with it 100%. Generally if you change those settings you will often need to redo your UI entirely.
I also use this CanvasScalerOrientationDriver
utility to make sharing UI for Landscape / Portrait easier. Read what it does carefully.
Apropos of nothing, here is my Jetpack Kurt Space Flight game, basically a first person lunar lander.
The little POI radar blip markers across the top of the screen are done with the above code snippet: