The question is answered, right answer was accepted
My Ray is going the wrong way
i have a top down view game, where you can move arounds with w,a,s,d and you make the character look around with the mouse(the camera is stationary), i wanted to shoot a ray to collide with the terrain, to then create a point so i can calculate my characters rotation. When i draw the ray in the debug mode, it just shoots backwards from the camera. How do i make it shoot to the ground?
#pragma strict
var Cam : Transform;
function Update()
{
Debug.DrawRay (Cam.position, Input.mousePosition, Color.green);
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
will help
i tried this now but diddnt work: var distancefcam : float; var cam : Camera; var hit: RaycastHit; var camPos : Transform;
function update ()
{
Debug.DrawRay(transform.position,transform.TransformDirection(Vector3.forward),Color.green);
var ray : Ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray,hit))
{
print("hit something at "+hit.distance+" meters");
distancefcam = hit.distance;
}
}
If you have setup cam right, that should work as intended, look at this page, and specifically the last example script (scroll all the way down), it is almost exactly what you are currently doing :o
Answer by EvilTak · Sep 02, 2015 at 10:45 AM
You will have to use Camera.ScreenToWorldPoint as Input.mousePosition contains the mouse position in screen space which you will need to convert to world sppace. You will have to note that the z component of the parameter vector in the ScreenToWorldPoint method contains the distance at which the point should be from the camera. So for example if your camera's z position is at -10 and your world is at z 0, the z component of the vector you pass to the method has to be 10.
im sorry, but it doesnt work for me, where exactly should i put it? thanks for your help btw!