- Home /
Can you figure out raycast origin position from RacyastHit?
I've got a world-space menu in virtual reality that works with raycasting (in my app you raycast from your fingertip). Whenever I hit an input field with my fingertip raycast, I want my keyboard (which is its own gameObject), to pop up in between the origin of the raycast and the menu, facing the player.
I have this (mostly) working by just lerping between Camera.main.transform.position and raycastHit.point, but I'd really like it to be between the fingertip which raycasted and the menu which was the raycastee.
In a raycastHit object, you get racycastHit.point and raycastHit.distance for free. You don't get the origin point of the raycast, nor, as far as I can see, do you get the actual direction of the raycast. You get the normal of the plane which you hit, which is not enough considering the menu could be at any angle when you hit it with a raycast.
tldr, is there a way to extrapolate the Vector3 origin of your raycast from raycast hit info?
Answer by arichards · Jul 17, 2019 at 04:57 PM
Usually you'll have the raycast (and the position passed into the raycast) still in scope when you call the Raycast method. Is this not the case? Maybe there's some way to capture those values?
Edit: See comment below. Editing to add potential solution:
Can your Raycast UnityEvent pass an instance of a class that contains both a Raycast and a RaycastHit? Or you can use a .NET event to pass more than one parameter. The code would be:
// RaycastTrigger.cs
public event Action<Raycast, RaycastHit> RaycastHitOccurred = delegate {};
// Invoke the event:
RaycastHitOccurred(myRaycast, myRaycastHit);
// Consumer.cs
private void Start()
{
raycastTriggerInstance.RaycastHitOccurred += HandleRaycastHitOccurred;
}
private void HandleRaycastHitOccurred(Raycast raycast, RaycastHit raycastHit)
{
// Do stuff
}
Not in my case. When my raycasting script hits a viable object, it looks for a "RaycastTrigger" component which invokes a UnityEvent, which obviously only passes the RaycastHit onwards to whatever script wants it.
I think it may be enough to just spawn the keyboard a little bit below the camera
Answer by tuf91497 · Jul 22, 2019 at 04:14 PM
A simpler answer for my solution has been to add an invisible anchor game object onto my menu keyboard at the point that I want it to spawn, and then to just move my keyboard to that position
A totally valid approach! I use empty transforms for that all the time.
Your answer
Follow this Question
Related Questions
Raycast not working 2 Answers
My raycast is ignoring my tilemap collider 0 Answers
Raycast detects box collider, but not capsule collider 0 Answers
Using Ray cast for click to move 2 Answers
Play Animation on Raycast *open and close some objects* 0 Answers