- Home /
Random X posistion between left and right edges of screen 2D
My goal is to have a app with characters running at you and you dodging but I want it to be universally good for tablets and phones. Preferably C# but java script is fine. What i want is having the character spawn at random position between the left edge of the screen and the right.
You will probably need to be way more specific. But, you can take the Screen.Width and multiply it by a RandomRange(0,1). And, that would give you a random X/width value of the screen, that is catered to all resolutions/platforms. Look at the $$anonymous$$athClass, because I think there is a Random01() method that is specifically, 0-1.
Hope this helps.
-Dwayne Pritchett
Answer by whaleinthesea · Aug 10, 2015 at 03:50 PM
vector3 v3Left = new Vector3(-0.15f, .5f, 10); //10 is the distance from the camera
v3Left = Camera.main.ViewportToWorldPoint(v3Left);
vector3 v3Right = new Vector3(Screen.width,0,0);
v3Right = Camera.main.ScreenToViewportPoint(v3Right);
v3Right = new Vector3(v3Right.x, .5f, 10);
v3Right = Camera.main.ViewportToWorldPoint(v3Right);
For me, this worked v3Left.x is the left edge of the screen and v3Right.x the right edge.
.15f how does that work to to detect a posistion also how wold I go about make a transform.posistion (random between edge left and edge right)
new Vector3(-0.15f, .5f, 10)
is a viewport a viewport starts at(0,0)left under. So (-0.15f, .5f, 10) is not exactly left under.
And for your second question here is the code: float f_random = Random.Range(v3Left,v3Right+1);//Random.Range give a float between first argument(v3Left)(included) and second argument(v3Right)(excluded, but we want that it can also spawn at the very right so we add +1 to it) transform.position = new vector3(f_random,y,z);//f_random is a random x position between the left and right position of the screen. Just replace the y and z with your own values
'
So the in one line it will be: transform.position = new vector3(Random.Range(v3Left,v3Right+1,y,z));
I hope this helped you.
Your answer
Follow this Question
Related Questions
Is there a way to determine Android physical screen size? 5 Answers
How to adjust the screen for many types of screens in Android? 1 Answer
How can i run a Unity Build on my PC, but use my phone as second screen, (Cheapskate Oculus-Like) 2 Answers
Best way to sync between different mobile devices? 1 Answer
How to do .9 scale for scaling screen? 0 Answers