Reputation: 484
I am trying to spawn a 2d image sprite in the screen in random position:
tex = Resources.Load<Texture2D>("pig") as Texture2D;
Sprite sprite = new Sprite();
sprite = Sprite.Create(tex, new Rect(0, 0, 250, 150), new Vector2(Random.Range(-1.5f, 1.5f), Random.Range(-1.5f, 1.5f)));
GameObject newSprite = new GameObject();
newSprite.AddComponent<Rigidbody2D>();
newSprite.GetComponent<Rigidbody2D>().gravityScale = 0f;
newSprite.AddComponent<ObjectMovement>();
newSprite.AddComponent<SpriteRenderer>();
SR = newSprite.GetComponent<SpriteRenderer>();
SR.sprite = sprite;
However, The placement of the sprite is not accurate and it being spawned in a tiny area, I want it to be in any point in the screen, What should my random range be?
Upvotes: 1
Views: 2504
Reputation: 125455
You have to convert view to world point with Camera.main.ViewportToWorldPoint
then you can use 0 to 1 to represent the screen size with .5 being the middle point.
Don't try to change the position from Sprite.Create
. Do it after creating the sprite. Remove the random code in that line of code. The only thing to add is
newSprite.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Camera.main.nearClipPlane + 15f));
I will use a code from your last question to answer to make sure there is no other problem in your current code. Tested and it works.
Texture2D tex = Resources.Load<Texture2D>("pig") as Texture2D;
Sprite sprite = new Sprite();
sprite = Sprite.Create(tex, new Rect(0, 0, 250, 150), new Vector2(0.5f, 0.5f), 40);
GameObject newSprite = new GameObject();
newSprite.AddComponent<Rigidbody2D>();
newSprite.GetComponent<Rigidbody2D>().gravityScale = 0f;
//newSprite.AddComponent<ObjectMovement>();
newSprite.AddComponent<SpriteRenderer>();
SR = newSprite.GetComponent<SpriteRenderer>();
SR.sprite = sprite;
SR.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Camera.main.nearClipPlane));
Upvotes: 2