- Home /
How to get information from raycast?
I'm making an FPS, right now I'm working on picking up guns on the floor. I got it to fully function by using the function "OnMouseEnter" and "OnMouseExit", but I just used those for testing purposes, now I want a raycast from the camera and if the raycast hits a gun, it switches the weapon. I was looking at the scripting reference but I couldn't find enough information on RayHit, or something like that. I already know how to cast a raycast, but I don't know how to get information from it, so I need help with that. All I need to know is how to check if the raycast is with a gun. I'm using javascript. Thanks!
This will be in C#, sorry I know 0 javascript. I will try to make it as easy to follow as possible because I know that I have learned from javascript even though I know none.
First you want to cast a ray from your camara, probably cast to a distance straight forward so you'd need:
public float rayCastDistance = 100f; //or whatever distance you want
public RaycastHit yourHitInfo;
Ray rayOrigin = Camera.main.ScreenPointToRay (new Vector3 (Screen.width / 2, Screen.height / 2, 0));//sets the rays origin to the middle of your screen
then, now that those are declared:
if (Physics.Raycast (rayOrigin, out yourHitInfo, rayCastDistance))
{
//do something with yourHitInfo like
if(yourHitInfo.collider.gameObject.tag=="gun")//if your raycast hits a gameObject tagged gun
{
//switch weapon
}
}
Answer by mpavlinsky · Feb 16, 2012 at 10:35 PM
You need to use information from your camera when generating the raycast like:
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.rotation, 1000)) {
Debug.Log("Hit.");
}
Your answer
Follow this Question
Related Questions
How to get a Vector3 from a RaycastHit variable? 1 Answer
Fall collision force with help of raycast 0 Answers
Exclude tag from raycast 1 Answer
Need Help with RayCast. No Vector? 1 Answer