How to Raycast from Camera View Point?

Hey all, I looked at a bunch of questions but nothing seemed to answer my question. How do I Raycast towards something I’m looking at? Also, how would I place a cube at the place where the raycast hits? My code right now is:

 RaycastHit hit;
    void Update () {
    	    if (Input.GetButtonDown("Fire1")){
              bool doesCollide = Physics.Raycast(transform.position, transform.forward *10, out hit, 10);
                GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
	            cube.transform.position = hit.transform.position + hit.normal;

But this tends to give weird results with cubes being places behind or in weird places. Also this script is attached to an object which is a attached my main camera (I don’t know if that is the right terminology). Thanks in advance for your help.

On this line:

    cube.transform.position = hit.transform.position + hit.normal;

I’m not sure why you’re adding the collision normal? More importantly, the base position of the object that was hit isn’t necessarily quite the same as the point of impact. You probably want to use hit.point instead.

You asked about raycasting from the camera. If you want to cast a ray through a specific point on the screen, you could use Camera.ScreenPointToRay(). I haven’t tried casting a ray through a specific object in the scene, but looking at this I imagine you might be able to use something like so:

	var origin = Camera.main.transform.position;
	var ray = new Ray( origin, transform.position - origin );

@rutter is right, at least almost ;)

With `hit.transform` you access the object you've hit. `.position` will just return the pivot point of that object. That's not what you need. Take a look at the RaycastHit struct. It has a member called `.point` which hold the actual hit position in world space coordinates.