2
\$\begingroup\$

enter image description here

I need to send a raycast from my camera which is parallel to the plane (Ground) and in the same direction of its forward vector (Represented by the black color vector)

I cant use world space direction because the global forward vector of the camera points at the same direction no matter how much I rotate it (Since its a VR camera)

I tried to use Vector3.ProjectOnPlane, but not sure how it works.

Can someone help me?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

So, you want to get a forward vector parallel to the ground plane relative to the camera's rotation, from what I can get.

The solution is as simple as using Vector3.Cross(Vector a, Vector b), it is not commutative, so you'll have to give the vectors in the correct order. What the cross product gives you, is a vector C perpendicular to 2 vectors A and B. So, both vectors you'll have to pass as parameters in the function are the camera's transform.right and the plane's normal (as an Y vector) as A and B respectively, so you get a forward vector parallel to the ground's plane.

One of the ways to get a ground's normal is by using Physics' API functions such as Raycast, Spherecast, Boxcast, etc., where you can obtain the RaycastHit information of the ground you are contacting.

For the sake of a simple example, you could try this with Raycast:

public class GetForwardVector : MonoBehaviour
{
    public LayerMask mask;
    public float distance;
    public Vector3 forward;

    public void Update()
    {
        RaycastHit hit;

        if(Physics.Raycast(transform.position, -transform.up, out hit, distance, mask))
        {
            forward = Vector3.Cross(transform.right, hit.normal);
        }
    }
}

Here, if the script was attached to the camera, a ray is casted from the camera's position, taking the camera's relative down direction, to obtain the information of the ground below it.

Hope it helps.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .