Hide trees when hiding the player

724 views Asked by At

I have created a 3D game in unity with terrain and some models, where the player can go anywhere he wants and the camera follows him.

my problem is when the user is behind a tree, how do I make the tree transparent?

I have already done it to the other models with Ray casting but the trees are part of the terrain and therefore I get the terrain material and not the specific tree.

any ideas?

thanks in advance

2

There are 2 answers

0
AudioBubble On

Well the best solution would be to start a Ray from camera to forward, and then put the camera a bit farther than the collision point, so that you can't see the tree.

Ray ray = new Ray(oldCam.position, oldCam.forward);
RaycastHit hit;

if (Physics.Raycast(ray, out hit, 5)){
cam.position = hit.point + oldCam.forward;
} else
cam.position = oldCam.position;

Remember to put the old camera position from where should be in order that the camera doesn't go away and stays there, and that the camera and old camera has the same code of position and rotation before this happens and then you just change their position. I mean I don't know if it's okay but you can take conclusions from this.

Sorry for mistakes I'm from Spain.

0
Hamza Tahir On

Indentifying issue

The trees are the part of the terrain and if you need to make trees you can easily do it . The trees will have a class of prefab and whenever the gameobject collide with any of the tree the collision task or say event would perform

solution

Thousands of trees could be created easily at the random location of the terrain and then the collision could easily be done by tagging and the code for the making trees would in the collider code. The trees will be disabled . The Ienumerator can be applied in the update method . The waitForSeconds(30) will wait for 30 seconds and then the code

gameobject.setactive(true)

will bring back the trees to their respective positions

code for creating trees at random location in start method

 public GameObject trees;
     for (int i = 0; i < 300; i++)
        {
            Vector3 localPosition = new Vector3(Random.Range(-200, 100), 0 , Random.Range(-200, 100));
            Instantiate(trees, localPosition, Quaternion.identity);
        }