- Home /
Initiate RayCast From Center of Camera?
Hello,
How would I go about Initiating a ray cast from the center of the screen (camera). Right now I am initiating from the mouses position:
function Update () {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 500))
Debug.DrawLine (ray.origin, hit.point);
var objectTouching = hit.collider.name;
print(objectTouching);
currentObjectOver = hit.collider.gameObject;
}
Thanks,
Ollie
Answer by Bunny83 · Feb 07, 2011 at 04:28 PM
It's quite easy since that's the "normal" way to raycast:
var cam : Transform = Camera.main.transform;
if(Physics.Raycast (cam.position, cam.forward, hit, 500))
or if you need the Ray use:
var cam : Transform = Camera.main.transform;
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 500))
This is not working for me, I am getting this error.
UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration.
is this cod C# or JavaScript? im running Java as main.
@SimpleGiant:
This is of course UnityScript (Unity's Javascript dialect) since the question was using it as well. This code works pretty well inside a function of course. You probably used it outside a function where you usually declare your member variables.
I suggest you watch some very basic coding tutorials about scripts and classes. If you don't know that a declaration is and what's executable code you won't get anywhere.
Answer by Simple · Feb 07, 2011 at 04:16 PM
var ray : Ray = Camera.main.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit : RaycastHit;
Physics.Raycast (ray, hit);
Vector3(0.5,0.5,0) uses x = 0.5 and y = 0.5 because Viewport vectors are normalized(which means they take value from 0 to 1). So, it will be the middle of camera viewport.