I’m creating a RTS style game where the player can choose from a toolbar at the bottom to choose what piece they would like to place on the game board. How do I instantiate an object to the position where the mouse is clicked. I know I have to use raycast but I’d like to see how it would work in this instance. Don’t worry about creating the toolbar.
Get a reference to the board’s collider, and use this (I’ll assume your board’s collider is assigned to boardCollider
, and that your prefab is assigned to myPrefab
):
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (boardCollider.Raycast(ray,out hit,Mathf.Infinity)) {
Instantiate(myPrefab,hit.point,Quaternion.identity);
}