0

I have a code that allows to position an object onto the other object by Raycast. Obviously, I am using Mesh Collider so everything works fine.

Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        if (hit.collider.gameObject.GetComponent<SelectableTrunk>())
        {
            RandomSTrunk.position = hit.point; 
        }
    }

My question is the next. Is it possible to place the object (as I did) and then do one more raycasting to place the other object onto the already placed one?

When I am trying to do that - The mesh collider on the first object is breaking everything and nothing works.

  • static bool RayCast ( Vector3 orgin , Vector3 direction , out RayCastHit hitInfo , float distnace=Mathf.Infinity , int layerMask=DefaultRaycastLayers ); The first parameter is the origin of the ray collision detection; The second parameter is the direction vector of ray detection; The third parameter is out type, which is used to get the return value of collision detection; The fourth parameter is the ray length of collision detection; The fifth parameter is collision detection only on the specified layer – Housheng-MSFT May 11 '22 at 02:13

1 Answers1

0

Specify a layer for the hit object and then follow the code below:

public LayerMask hitPlaceLayer;

void RayCast()
{
    // first ray cast
    if (Physics.Raycast(transform.position, transform.forward, out var hit, hitPlaceLayer.value))
    {
        RandomSTrunk.position = hit.point; 
    }
    
    // second raycast
    if (Physics.Raycast(transform.position, transform.forward, out hit, hitPlaceLayer.value))
    {
        otherRandomTrunk.position = hit.point; 
    }
}

define layer for Hit place object:

enter image description here

Layer mask for raycasts: enter image description here

KiynL
  • 4,097
  • 2
  • 16
  • 34