Search code examples
c#unity-game-engineinstantiation

How to get rounded x/z position of mouse, along with a certain y position, then instantiate an object there?


I'm trying to make little building game, where I want to take the x/z position of the mouse along with a certain y position, then round those to integers. Then I instantiate an object at that final position. It keeps spawning the block at a location hundreds off, for example when I click at 0,0,0 it spawns a block at 580.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Building : MonoBehaviour
{
    public GameObject Block;

    void Update(){
        int mousePosX = Mathf.RoundToInt(Input.mousePosition.x);
        int mousePosZ = Mathf.RoundToInt(Input.mousePosition.z);

        if(Input.GetButtonDown("Fire1")){
            Instantiate(Block, new Vector3(mousePosX, 0.15f, mousePosZ), Quaternion.identity);
        }
    }
}

Solution

  • In your case, because you're trying to find the point on the ground to build your Block, you'll first need to set up your ground with a Collider ( a box collider, covering the ground is a good option).

    Now, modify your Update statement to look like this:

    void Update ( )
    {
        if ( Input.GetButtonDown ( "Fire1" ) )
        {
            if ( Physics.Raycast ( Camera.main.ScreenPointToRay ( Input.mousePosition ), out var hit ) )
            {
                var point = hit.point;
                point.x = Mathf.RoundToInt ( hit.point.x );
                point.z = Mathf.RoundToInt ( hit.point.z );
                point.y = 0.15f;
    
                Instantiate ( Block, point, Quaternion.identity );
            }
        }
    }
    

    What you're now doing is find a ray from the camera, through the mouse position, in to the scene. Where it hits the ground is the hit.position Vector3. It's at THAT point that you want to then round to an integer value, and Instantiate.

    In addition, you may as well only check your mouse position IF you've pressed the fire button.