Home > Enterprise >  Raycast along objects face while keeping the ray horizontal in unity
Raycast along objects face while keeping the ray horizontal in unity

Time:12-04

I am attempting to raycast along objects faces in order to create a mesh of a liquid surface in containers made from objects no matter their rotation. Currently im taking the transform.up/right/forward using the X and Z but setting Y to 0 for the direction of the raycasts. This seems to work unit the object is rotated on multiple axis.

Example of error

You can see here that the direction of the green raycast is not along the face. Im thinking a solution may have to do with taking the y value I am ignoring and applying it to the x and z in some way.

This is for a concept where the player will build their own container out of primitive colliders, so it matters that it works no matter the rotation of the object.

CodePudding user response:

If you have a normal of the surface you're interested in, you can use Vector3.Cross to find a tangent which is also orthogonal to up. Just be sure to check if the result is (0,0,0) in the event up and the normal are colinear, then you can pick an arbitrary world horizontal direction.

public class test : MonoBehaviour
{
    void Update()
    {
        Vector3 dir = HorizontalTangent(transform.up);
        Debug.DrawLine(transform.position, transform.position   dir,Color.red, 0f);
    }

    Vector3 HorizontalTangent(Vector3 surfaceNorm)
    {
        Vector3 res = Vector3.Cross(Vector3.up, surfaceNorm);
        if (res == Vector3.zero) res = Vector3.right;
        return res;
    }
}

example

  • Related