Search Unity

Question WorldToScreenPoint only works after entity comes on screen

Discussion in 'Scripting' started by ClearRoseOfWar, Apr 3, 2022.

  1. ClearRoseOfWar

    ClearRoseOfWar

    Joined:
    Sep 6, 2015
    Posts:
    89
    So I want to display where each enemy is on the HUD when the enemies are offscreen. This works fine if the enemy has been on camera -- but typically the enemy is killed when met, so

    TLDR:
    the point is to show the players where the last few enemies are:


    Code (CSharp):
    1.  
    2. // for each mob left
    3. for (int i = 0; i < finalMobs.Count-1; i++)
    4. {
    5.      // if they have health
    6.      if(finalMobs[i].health > 0){
    7.           Vector3 objectLoc = _mainCamera.WorldToScreenPoint(finalMobs[i].gameObject.transform.position);
    8.           Vector2 dist = new Vector2(
    9.                        Vector3.Distance(new Vector3(Screen.width / 2, 0f, 0f), new Vector3(objectLoc.x, 0f,0f)),
    10.                        Vector3.Distance(new Vector3(0f, Screen.height / 2, 0f), new Vector3(0f, objectLoc.y, 0f))
    11.           );
    12.  
    13.           if(dist.x < Screen.width / 2)
    14.                enemyMarkers[i].position = new Vector3(objectLoc.x, enemyMarkers[i].position.y, enemyMarkers[i].position.z);
    15.  
    16.          if(dist.y < Screen.height / 2)
    17.               enemyMarkers[i].position = new Vector3(enemyMarkers[i].position.x, objectLoc.y, enemyMarkers[i].position.z);
    18.  
    19.      enemyMarkers[i].gameObject.SetActive(true);        
    20.      }
    21.      else{
    22.           enemyMarkers[i].gameObject.SetActive(false);
    23.      }
    24. }
    The above code works fine if the mob spawns inside the camera's view; But if the mob spawns outside the cameras view the marker doesn't follow*

    Once the mob has been on camera at least once, the marker then follows*.

    *follow - (stays at the edge of the screen)
    Thank you for your time.
     
    Last edited: Apr 3, 2022