I want to create 2d game. Structure of objects
"View" present a square where everything happens.
"Initial" This is the same square with a mask
"SquareList" is empty panel.
Why am I doing this?
I created a script where when I click on the screen, a new square is added to the SquareList. SquareList is the parent. I created a script to determine the position of the cursor.
createPos = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
Next, I want to set for new object position = cursor position.
Cursor.position equivalent = (562,1134 / 242.6486) But the new object get position (94931.29 / 103365.6 / -17280)
But if I set position of new object to = new Vector(0,0); Then everything is fine
What is the problem?
Input.mousePosition
returns position in pixel-coordinate. You have to use Camera.main.ScreenToWorldPoint
to convert it to world position then assign that to the object. If 3D Object, add an offset to it before converting with ScreenToWorldPoint
.
public GameObject prefab;
public float offset = 10f;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 clickPos;
clickPos = Input.mousePosition;
clickPos.z = offset;
clickPos = Camera.main.ScreenToWorldPoint(clickPos);
GameObject obj = Instantiate(prefab, clickPos, Quaternion.identity);
}
}