RTS Building : Buildings following the mouse [C#]

Hi everybody !
I’m making an RTS game and i have a problem for the building system : my buildings move only on the x axis…

This is my actual code :

using UnityEngine;
using System.Collections;

public class Building : MonoBehaviour{

    public GameObject[] structuresTypes;
    Vector3 mousePos;
    GameObject _structureTypes;
    GameObject pre_structure;
    bool isBuilding = false;


    void Update()
    {
        float x = Input.mousePosition.x;
        float z = Input.mousePosition.z;
        float y = 0.25f;
        mousePos = new Vector3(x, y, z);

        if(isBuilding == true)
        {
            pre_structure.transform.position = mousePos;
            if (Input.GetMouseButtonDown(0))
            {
                Destroy(pre_structure);
                Instantiate(_structureTypes, mousePos, Quaternion.identity);
                isBuilding = false;
            }
        }
    }


    public void SelectFarm()
    {
        _structureTypes = structuresTypes[0];
        isBuilding = true;
        Destroy(pre_structure);
        pre_structure = (GameObject)Instantiate(_structureTypes, mousePos, Quaternion.identity);
    }


}

Thank you, bye
xyHeat

The mouse uses a Vector2 to position. I know it takes and returns a Vector3 for its position, but really the Z is unused. When you get your mouse position you are getting the position of it on the ScreenSpaceUIOverlay (the ‘Canvas’ object that gets drawn over the scene). The mouse will never return its position in the world space. There are functions for finding a world position relative to the screen and a screen position (like the Mouse) relative to the world. Remember, when going from Screen space to World space (or back), you need a camera. What you want to do is something LIKE:

         Vector3 calculatePosition;
    
         void Update()
         {
             calculatePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    
             if(isBuilding == true)
             {
                 pre_structure.transform.position = calculatePosition ;
                 if (Input.GetMouseButtonDown(0))
                 {
                     Destroy(pre_structure);
                     Instantiate(_structureTypes, mousePos, Quaternion.identity);
                     isBuilding = false;
                 }
             }
         }

What this code will do is draw a line from the camera, at that position on the screen, and return the point of the first object it hits in the game world.

ProTip: You probably don’t want to have every building in the scene calculating the Mouse’s position every frame. You can solve this problem by creating a Mouse ‘Singleton’, and having that singleton calculate its position, then use that stored information in the rest of your code.