Raycast coming from center of camera

I need a raycast to come out from the center of my camera out into the world and stop after a certain limit. I’ve never messed with raycasts before and still trying to learn 3D programming, so this is kind of confusing to me. I currently have some script but it’s not working very well for me, but here is my current code.

using UnityEngine;
using System.Collections;

public class Raycast : MonoBehaviour {
   
    Ray RayOrigin;
    RaycastHit HitInfo;
   
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
       
        if(Input.GetKey(KeyCode.E)){
            RayOrigin = Camera.main.ViewportPointToRay(new Vector3(0,0,0));
            if (Physics.Raycast(RayOrigin,out HitInfo,100f)){
                Debug.DrawRay(RayOrigin.direction,HitInfo.point,Color.yellow);
            }
        }
       
    }
}

Just use the camera transform’s position and forward vectors.

if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out HitInfo, 100.0f))
3 Likes

Thanks, I did what you said but now it’s not creating a ray at all? Sorry for not being able to understand this! Ray casting is hard for me :confused:

Do you mean it’s not drawing the ray? Just replace the parameters in your Draw call as well.

Transform cameraTransform = Camera.main.transform;

if(Physics.Raycast(cameraTransform.position,cameraTransform.forward, out HitInfo, 100.0f))
     Debug.DrawRay(cameraTransform.position, cameraTransform.forward * 100.0f, Color.yellow);
2 Likes

Wowowow, I dind’t think of that at all, jeez! I’m not too great at this ahaa >->