[SOLVED]Casting ray from centre of screen? (C#)

Hi all,

Sorry in advance for this simple question.

I am working on a FPS and want to be able to see what objects the player is looking at (at the centre of the screen) within a certain range. All the objects i need to be able to see are in their own layer.

I’ve been trying to use:

Physics.Raycast(transform.position, Vector3.forward, hit, 100.0f)

but with little success.

Could someone please help me out with this.

EDIT:

if ( Physics.Raycast(transform.position, Vector3.back, out hit, 50.0f)) 
        { 
            distance = hit.distance; 
            collider1=  hit.collider; 
            Debug.Log(distance); 
            Debug.DrawLine(transform.position, hit.point, Color.red); 
        }

This seems to be working and returning the object hit BUT the ray is ALWAYS shooting in the same direction. I have attached the script to the main camera and now need to change ‘Vector3.back’ to something else?! Ive tried ‘transform.rotation.eulerAngles’.

How can i make the Ray shoot in the direction of the camera?

I think the actual problem is due to the First Person Controller prefab returning the Y Rotation and the Main Camera within returning the X.

Many thanks in advance,
Matt. BTW, i’m using C#

I can’t test this at the moment but how about:

Should throw a ray from the center of the screen no matter what the aspect ratio.

var ray = camera.ScreenPointToRay (Vector3(Screen.width/2,Screen.height/2,0));
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
            distance = hit.distance;
            collider1=  hit.collider;
            Debug.Log(distance);
            Debug.DrawLine(transform.position, hit.point, Color.red);
        }

Koko

Check out Camera.ViewportPointToRay. The example in the docs sounds like what you’re looking for.

Perfect!! That’s what I needed. Many thanks.

Matt.