Created
March 5, 2023 10:51
-
-
Save CodeSmile-0000011110110111/de9150bf5d6ff4a7298f44f54e7721b8 to your computer and use it in GitHub Desktop.
Ray extension method that tests whether a ray hits a "virtual" plane
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace CodeSmile | |
{ | |
public static class RayExt | |
{ | |
const float MinDenominator = 0.00001f; | |
/// <summary> | |
/// Test intersection of ray with a virtual XZ plane with given plane height (default: 0). | |
/// </summary> | |
/// <param name="ray"></param> | |
/// <param name="intersectPoint"></param> | |
/// <param name="planeY"></param> | |
/// <returns></returns> | |
public static bool IntersectsVirtualPlane(UnityEngine.Ray ray, out Vector3 intersectPoint, float planeY = 0f) | |
{ | |
intersectPoint = Vector3.negativeInfinity; | |
// try pick the virtual XZ plane (with Y = planeY) | |
var planeNormal = Vector3.down; | |
var planePoint = new Vector3(0f, planeY, 0f); | |
var denominator = Vector3.Dot(ray.direction, planeNormal); | |
var intersects = denominator >= MinDenominator; | |
if (intersects) | |
{ | |
var distanceToPlane = Vector3.Dot(planePoint - ray.origin, planeNormal) / denominator; | |
intersectPoint = ray.origin + ray.direction * distanceToPlane; | |
} | |
return intersects; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment