How can I spawn an object where I clicked in a 3D space, but spawn it in a 2D location?,How can I spawn objects where I click in a fixed position on 2 axis?
I have a game where I have an object sat on a 3D plane and I want to click above it to drop an object. Wherever I click I want the object to drop where I clicked on the Z-axis, but on a fixed position on the X and Y axis.
Please see the below image:
I am using the following code to do that, which I have attached to my long cube (the platform).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class clickBehaviour : MonoBehaviour
{
public GameObject GameCube;
Ray ray;
RaycastHit hit;
// Update is called once per frame
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (Input.GetButtonDown("Fire1"))
{
GameObject obj = Instantiate(GameCube, new Vector3(-75, 9, hit.point.z), Quaternion.identity) as GameObject;
Debug.Log(hit.point);
}
}
}
}
GameCube
refers to the GameObject of the smaller cube on top of the platform.
What seems to be happening, is that when the user clicks a block appears. If the mouse is low down the screen on click then it appears where it should be. If it is higher up the screen it appears off in one direction away from where it should be.
I believe this is because Unity is picking up the click way in the background, but I'm dropping the new cube in the foreground. Because of this the Z coordinate is then quite a way off. The further in the background I click the further off it is.
How can I have the cubes always appear in the correct position, above the platform? I'm guessing this is a common requirement, but struggling to work out how to do it, or what to Google to find out more info.
Thanks