Unity Physics

Hello Everybody . I have a code that is used to put some buildings in the ground .
I want my towers to be red , when they cant be placed and green when it is allowed . There is only one problem tho . My program stops working as soon as I implement Physics.raycast with distance . Let me show you what I mean .

“”"
private void HandlePlacemet()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(“ShootingRay”);
if (Physics.Raycast(ray, out var hitInformation))
{
objectToPlace.transform.position = hitInformation.point;
objectToPlace.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInformation.normal);
}
}
“”"

Code Like this is working fine , it is doing just exactly what you would think . It gets some points , and then it transforms the object to those points . Simple. However this seems to break everything .

“”"
private void HandlePlacemet()
{

//Lets say that the layerMask is 1<< 8; Doesnt matter . It is not the problem.
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(“ShootingRay”);
if (Physics.Raycast(ray, out var hitInformation,Mathf.Infinity,_layerMask))
{
objectToPlace.transform.position = hitInformation.point;
objectToPlace.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInformation.normal);
}

}
“”"

As soon as I imp[element the Distance , doesn’t matter what distance (10, 1000,1) it breaks.
It worked with 10 , I believe if I remember correctly but then it just spawnd the buildings in one place …
Any ideas ??? Very interesting problem

I’m a complete Unity novice but please put your code in code tags otherwise most people will refuse to help you :slight_smile:

1 Like

Ooh My baddd . How do I put it in tags ? Im newbie too :smile:. I have improvised with three " before the start and end of the code .

On your original question, where are you implementing Distance? I don’t see it. In the changed code you just provided the same default it already uses, but it looks like the real difference is you are providing a layerMask.

Since you think the issue is distance, but the only thing different is the layerMask, I’d suggest removing the layerMask and just testing with changes to distance to verify that is or is not the problem. When troubleshooting problems it is important to first isolate the issue, and part of that is staying away from changing multiple things at once, or you can end up not knowing which thing you changed is the source or solution to a problem, and make incorrect assumptions.