private void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (terrainCollider.Raycast(ray, out hit, Mathf.Infinity))
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.point;
cube.transform.localScale = new Vector3(50, 50, 50);
}
}
}
This is working fine when I click with the mouse on the terrain it will spawn a cube on that position I clicked with the mouse.
But now I added a plane a small size plane above the terrain the plane is about 0.5 higher from the terrain.
I want that I click with the mouse it will spawn the cube/s on the terrain but only if the mouse is inside the plane area. Not anywhere on the terrain like it is now but only on the plane area.
I mean that only when I click with the mouse somewhere on the plane area than spawn cube on the terrain.
On the top of the script I reference to my plane :
public CustomPlane plane;
And this is the CustomPlane script :
using UnityEngine;
[ExecuteAlways]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class CustomPlane : MonoBehaviour {
public float width = 1;
public float length = 1;
private float oldWidth;
private float oldHeight;
public void Start()
{
oldWidth = width;
oldHeight = length;
Create();
}
private void Update()
{
if(oldWidth != width || oldHeight != length)
{
Create();
oldWidth = width;
oldHeight = length;
}
}
private void Create()
{
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[4]
{
new Vector3(0, 0, 0),
new Vector3(width, 0, 0),
new Vector3(0, length, 0),
new Vector3(width, length, 0)
};
mesh.vertices = vertices;
int[] tris = new int[6]
{
// lower left triangle
0, 2, 1,
// upper right triangle
2, 3, 1
};
mesh.triangles = tris;
Vector3[] normals = new Vector3[4]
{
-Vector3.forward,
-Vector3.forward,
-Vector3.forward,
-Vector3.forward
};
mesh.normals = normals;
Vector2[] uv = new Vector2[4]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(0, 1),
new Vector2(1, 1)
};
mesh.uv = uv;
meshFilter.mesh = mesh;
}
}