Search Unity

Question Make a GameObject appear when AR Camera gets at a specific distance from it

Discussion in 'AR' started by petroslouca, Feb 6, 2021.

  1. petroslouca

    petroslouca

    Joined:
    May 17, 2018
    Posts:
    14
    Hi!

    I am utilizing ARFoundation in Unity and being trying to make an object appear, at a specific camera distance or less, from it. What is the best practice/approach to achieve this, taking into consideration possible offset(s) that need to be applied for better fine tuning during ray-casting process (to increase accuracy)?

    This is the code I've written, the script is attached to an empty GameObject with a Collider, thus with a successful hit at the predefined distance value (or less), the required GameObject appears...


    Transform hitTransform;

    void Update()
    {
    Ray ray = Camera.main.ViewportPointToRay(gameObject.transform.position);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
    {
    hitTransform = hit.transform;
    POI_DistancefromCamera = Vector3.Distance(Camera.main.transform.position, gameObject.transform.position);

    if (POI_DistancefromCamera <= 1)
    RayCastHitTrigger = true;
    }

    if (RayCastHitTrigger)
    {
    RequiredGameObject.SetActive(true);
    }


    Thank you!
     
    makaka-org likes this.
  2. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258
    Code (CSharp):
    1. Ray ray = Camera.main.ViewportPointToRay(gameObject.transform.position);
    This would be your first issue. The position of the GameObject is not a position in the Viewport (ScreenSpace) but a position in the Scene (WorldSpace).

    If your goal is to enable the GameObject if the camera is within a certain distance, and looking in its direction, the easiest way would be to skip raycasting altogether.

    The distance can be retrieved as you are doing above (Vector3.Distance(A, B)).
    The 'Look-Direction' can be calculated by comparing the direction to the GameObject (GameObject.position - Camera.position) with the Forward-Direction of the Camera (Camera.main.transform.forward). Both of these will be in World-Space (they are both directions though, so both have the Camera-position at (0,0,0)).

    Vector3.Angle(CameraForward, GameObjectDirection) will give you the (unsigned) angle between the two directions.
     
  3. petroslouca

    petroslouca

    Joined:
    May 17, 2018
    Posts:
    14
    Thank you! But skipping Raycasting is not what I had in mind, what would then be the actual code, needed to be implemented in the UPDATE function?
     
  4. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258