- Home /
Question by
lawrrennce · Nov 02, 2019 at 01:00 PM ·
c#instantiatemain camera
Instantiate prefab within main camera view
I want my object to instantiate within the main camera view but I cant get it to work, the main camera are constantly moving to the right following the player. Thanks in advance.
public GameObject bar;
Collider2D col;
void Start()
{
col = GetComponent<Collider2D>();
}
public void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(1);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Began)
{
Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
if (col == touchedCollider)
{
float spawnY = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);
float spawnX = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);
Vector2 spawnPosition = new Vector2(spawnX, spawnY);
Instantiate(bar, spawnPosition, Quaternion.identity);
}
}
}
}
Comment
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I want to put main camera floating 0 Answers
How to instantiate several objects from a single string 2 Answers
How to randomly instantiate other prefabs parallel? 1 Answer