- Home /
How can I use raycasthit and collider raycast to hit only if the mouse position is over a specific object ?
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;
}
}
Answer by joan_stark · Aug 24, 2021 at 07:27 PM
An easy way of doing this is adding a collider to your plane, and put it into an special layer. Then you can first cast a raycast to that layer, if it impacts, then you cast another raycast ignoring that specific layer. If it doesn't impact, you don't do nothing since you are not inside the plane.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Which setup should I use for spawning? 0 Answers
Multiple Cars not working 1 Answer
Gameobject collision with Terrain C# 4 Answers
Is it possible to convert a Collider into a Spawner? 0 Answers