Home > Net >  Unity Raycasting: "Camera.main.ScreenPointToRay" works, "new Ray(...)" does not
Unity Raycasting: "Camera.main.ScreenPointToRay" works, "new Ray(...)" does not

Time:01-02

right now I'm working on a planet generation project in the Unity engine. The problem I have happens when I want to place plants on the planet surface.

My approach is to cast rays from the center of the planet out towards the surface to get the positions of the plants (because the surface is no plain sphere, so I don't know the exact positions). But I don't get any hits.

So I tried several things to fix that. And what I found is quite strange for me. When I create a Ray using "new Ray", I get nothing. But with "UnityEngine.Camera.main.ScreenPointToRay" I get some expected hits. So it cannot be an issue about the GameObject layers.

For me it looks like using "new Ray" is buggy or something.

Anyone here to explain this?

    public void CreatePlants(List<PlantDefinition> plantSpeciesDefinitions)
    {
        foreach (PlantDefinition plantDefinition in plantSpeciesDefinitions)
        {
            directions = new Vector3[plantDefinition.maximumCount];
    
            for (int i = 0; i < plantDefinition.maximumCount; i  )
            {
                Vector3 direction = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
                direction.Normalize();
                directions[i] = direction;
    
                Ray ray = new Ray(planetCenter, directions[i]); // does not give any hits
                Ray ray2 = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition); // does give hits
    
                Physics.Raycast(ray2, out RaycastHit hit);
                    
                if(hit.collider != null) 
                    Debug.LogWarning($"Object hit: {hit.collider.gameObject.name}");
                    
            }
        }
    }

CodePudding user response:

By default raycasts in Unity do not hit the "inside" / backfaces of a Collider.

You start your ray inside a sphere and want to hit the surface from the inside.

You will have to enable enter image description here

  • Related