In a shader for Unity (hlsl) I'm looking for a way to project a vector(float3 or float4) onto a plane given the plane's normal direction. What I need is something equivalent to Unity's Vector3.ProjectOnPlane function: https://docs.unity3d.com/ScriptReference/Vector3.ProjectOnPlane.html
0
votes
1 Answers
1
votes
If your plane normal vector is normalized:
inline float3 projectOnPlane( float3 vec, float3 normal )
{
return vec - normal * dot( vec, normal );
}
If it's not:
inline float3 projectOnPlane( float3 vec, float3 normal )
{
return vec - normal * ( dot( vec, normal ) / dot( normal, normal ) );
}
Same formula, depending on GPU model & driver version can be either faster or slower:
inline float3 projectOnPlane( float3 v, float3 n )
{
float3 r;
r.x = n.y * n.y * v.x + n.z * n.z * v.x - n.x * n.y * v.y - n.x * n.z * v.z;
r.y = n.x * n.x * v.y - n.x * n.y * v.x - n.y * n.z * v.z + n.z * n.z * v.y;
r.z = n.x * n.x * v.z - n.x * n.z * v.x + n.y * n.y * v.z - n.y * n.z * v.y;
return r / dot(n, n);
}