So I am trying to make something like in Starcraft where you click on a button for a building that you want to place and it then an instance of that building will follow your mouse movements. I was looking up RaycastHit because I figured that’d be the best way to go about it. I wrote it out and all it does is Instantiate the cube that shows where the building will go. Here is the script that I have devised.
using UnityEngine;
using System.Collections;
public class BuildingPlacement : MonoBehaviour
{
public GameObject placementCube;
public Camera playerCamera;
private Vector3 startingMousePosition;
void Start ()
{
Instantiate(placementCube, new Vector3(0, 0, 0), Quaternion.identity);
startingMousePosition = Input.mousePosition;
}
void Update ()
{
if(Input.mousePosition != startingMousePosition)
{
RaycastHit hit;
Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
placementCube.transform.position = new Vector3(hit.point.x, 1, hit.point.z);
}
}
}
}
Also does anyone know a way to get the object to move like a grid? Basically what I mean is that when the mouse moves off of the cube, it will move over by the width/height of the object in the direction that the mouse is moving. Essentially in order to keep things lined up. Any help would be appreciated.