RaycastHit Position Changes According to Camera Position

Hi

We’re developing a level creator within unity. And as a first step we want to get the position of the place where the user touches so that we can start creating our platform in that level
For achiving this we’ve implemented the below code but the problem is, if we change the camera’s position , resulting position also changes.
What I actually want is, when a user touches a place in the object, regardless of the cameras position it should return the actual world coordinates of that point

void OnMouseDown () {

       //Debug.Log("MouseClicked-X:"+Input.mousePosition.x+"Y:"+Input.mousePosition.y+"Z:"+Input.mousePosition.z);

Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 6);
Vector3 worldPosition = mainCamera.ScreenToWorldPoint (mousePosition);

Ray ray = mainCamera.ScreenPointToRay(mousePosition);

RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
//Debug.Log("ConvertedMousePoint-X:"+hit.point.x+"Y:"+hit.point.y+"Z:"+hit.point.z);
int row = (int) Math.Ceiling((hit.point.x / sideOfGridCell));
int column = (int) Math.Ceiling((hit.point.z / sideOfGridCell));
Debug.Log ("SelectedCellRow:" + row + "Column:" + column);

} else {
Debug.Log ("NotHitted");
}


}

Thanks

instead of this:

Vector3 worldPosition = mainCamera.ScreenToWorldPoint (mousePosition);

Try this inside the if statement:

Vector3 worldPosition = hit.point;

This means you will not get a world position if the raycast doesn’t hit an object, but you will get the exact position of where the ray first collides with the object if it does.

I’m already using the hit.point inside the if statement as you can see in the code:

int row = (int) Math.Ceiling((hit.point.x / sideOfGridCell));
int column = (int) Math.Ceiling((hit.point.z / sideOfGridCell));

that worldposition variable is just for comparing the 2 positions.
But still it works incorrect when I’ve changed the camera’s position

What’s the reason for the 6 on this line?

Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 6);

I don’t see any reason for the mousePosition and worldPosition variables.

Your function block could start at the ray variable declaration with this:

Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

Does the shape of the collider match the surface that you are clicking?