- Home /
Duplicate Question
why is my raycast not working?
I am trying to send a ray from the mouse position to the ground and print somthing in the console, i have a tag called "terrain" on the terrain, do i need to add a label?`using UnityEngine; using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
//Vector3 fwd = Input.mousePosition;
Ray modelplacer = new Ray (Input.mousePosition, Vector3.down);
if (Physics.Raycast(modelplacer,out hit,10))
{
if(hit.collider.tag == "terrain")
{
print("There is something in front of the object!");
}
}
}
}`
I'm guessing you want this:
camera.ScreenPointToRay(Input.mousePosition);
Answer by robertbu · Nov 02, 2014 at 09:21 PM
The right solution will depend on what you are really trying to do here, but the core of your issue (a frequent question on UA) is that Input.mousePosition is in screen coordinates and Raycasts() are in world coordinates. Making a Ray from Input.mousePosition does not make sense. Depending on your situation you either want to so as AlwaysSunny suggests and use Camera.ScreenPointToRay() or you may want to use Camera.ScreenToWorldPoint() to generate the origin for your Ray.
Follow this Question
Related Questions
Something fishy with RaycastHit 1 Answer
Rays do not detect terrain and prefabs do not spawn where wanted 1 Answer
How can I can I cast a ray from a gameobject? 1 Answer
Raycast Not Working 3 Answers
Find gameobjects in a crosshair? 1 Answer