Sirwhite2015
Sirwhite2015

Reputation: 5

Unity 2D - moving an instantiated GUI element in canvas at certain speed regardless of canvas screen resolution

I'm trying to move an instantiated GUI element across the screen but all seems fine until I change the screen resolution to something larger like 2048 x 2732 iPad .. The GUI movement becomes slow.. What do you guys think is the perfect solution to this.. Please help.. This moves the GUI gameobject in the canvas rb.velocity = new Vector2 (speed, 0);

Upvotes: 1

Views: 942

Answers (1)

Fattie
Fattie

Reputation: 12631

Two two secrets here are

(1) You must understand Unity's canvas scaling system's scale mode

(2) and the "reference size" concept

Here's how ...

(1) A huge gotchya in Unity is that you must set your canvas to "Scale with screen size":

https://stackoverflow.com/a/38311402/294884

enter image description here

Please read the linked answer

(2) Note that indeed you choose your own reference resolution. 800x600 say is typical. It can actually be any number.

From there the calculation is easy.

You normally work in "screen widths per second".

float screenWidthsPerSecond = 2.5f;

means it would take 2.5 seconds to cross the entire screen, left to right.

You should then have no trouble with the calculation. Let's say you have the reference resolution set on 800x600. Your code will be like:

 float referenceResolutionWidth = 800f;
 float secondsThisFrame = Time.deltaTime;

 distanceThisFrame =
    ( referenceResolutionWidth / screenWidthsPerSecond )
    * secondsThisFrame;

and that's how far you would move it that frame.

(Note that normally of course you know the reference width you set for the project, 800 in the example. If you wanted you could look it up once and cache it, it is

 refWidth = yourCanvas.GetComponent<CanvasScaler>().referenceResolution.x

)

Upvotes: 3

Related Questions