I made some code to check when the player camera is in front of a quad and the camera point is projected on a plane that faces the same direction as the quad.
The vertices go around the quad clockwise order.
I used dot product to check if the camera point is inside the quad.
I wanted to use a cross product with it but, I had a problem with vector 3 and int in the if statement.
The code seems to work.
How do I use a cross product with the if statement in the loop?
???
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointInPolygon : MonoBehaviour
{
private Mesh mesh;
public bool PointInside;
private Vector3 Point;
private Vector3 CamPoint;
public Vector3[] vertices;
public List<Plane> Planes = new List<Plane>();
public List<Vector3> tpvertices = new List<Vector3>();
// Start is called before the first frame update
void Start()
{
mesh = GetComponent<MeshFilter>().sharedMesh;
int[] triangles = mesh.triangles;
vertices = mesh.vertices;
for (int i = 0; i < triangles.Length; i += 3)
{
Vector3 p1 = vertices[triangles[i + 0]];
Vector3 p2 = vertices[triangles[i + 1]];
Vector3 p3 = vertices[triangles[i + 2]];
Vector3 tp1 = transform.TransformPoint(p1);
Vector3 tp2 = transform.TransformPoint(p2);
Vector3 tp3 = transform.TransformPoint(p3);
Planes.Add(new Plane(tp1, tp2, tp3));
}
for (int i = 0; i < vertices.Length; i++)
{
Vector3 p = vertices[i];
Vector3 tp = transform.TransformPoint(p);
tpvertices.Add(tp);
}
}
// Update is called once per frame
void Update()
{
CamPoint = Camera.main.transform.position;
Point = Vector3.ProjectOnPlane(CamPoint, Planes[0].normal);
for (int i = 0; i < tpvertices.Count; i++)
{
int j = i + 1;
if (j == tpvertices.Count)
{
j = 0;
}
Vector3 tp1 = tpvertices[i];
Vector3 tp2 = tpvertices[j];
float DotProduct = Vector3.Dot(Point - tp1, tp2 - tp1);
PointInside = true;
if (DotProduct < 0)
{
PointInside = false;
break;
}
}
if (PointInside == true)
{
Debug.Log("Point inside");
}
}
}