Search Unity

WorldtoViewportPoint problems.

Discussion in 'Scripting' started by angel_m, Sep 26, 2008.

  1. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    I am trying to implement a Lock-targeting texture with the WorldToViewportPoint function but it does not work ( the texture is not on the enemy-target position but sometimes in the screen top corner or most of the times not visible at all).This is the code simplified:

    /code/
    var target : Transform;
    var locktexture : Texture;
    var micamera : Camera;

    function Update () {

    var viewPos = micamera.WorldToViewportPoint (target.position);

    DrawTexture(Rect(viewPos.x,ViewPos.y,32,32),locktexture)
    }
    /code/

    I have tried with OnGUI() function instead of Update() but it is the same.
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    WorldToViewportPoint is for getting coordinates in viewport space, which is normalized (i.e., always between 0 and 1). GUITextures use viewport space; in fact you might prefer to use GUITextures for this sort of thing. In which case you'd use

    Code (csharp):
    1. var target : Transform;
    2. var micamera : Camera;
    3.  
    4. function Update () {
    5.     transform.position = micamera.WorldToViewportPoint (target.position);
    6. }
    and attach that to the GUITexture object. If you really do want to use Graphics.DrawTexture, that has to be in OnGUI, and you'd use WorldToScreenPoint, because DrawTexture needs screen coordinates...except the Y coordinate needs to be inverted (and this is why I prefer GUITextures for stuff like this, it's just easier):

    Code (csharp):
    1. var target : Transform;
    2. var locktexture : Texture;
    3. var micamera : Camera;
    4.  
    5. function OnGUI () {
    6.     var viewPos = micamera.WorldToScreenPoint (target.position);
    7.     Graphics.DrawTexture(Rect(viewPos.x-16, Screen.height-viewPos.y-16, 32, 32), locktexture);
    8. }
    --Eric
     
  3. angel_m

    angel_m

    Joined:
    Nov 4, 2005
    Posts:
    1,160
    It works now.
    Thank you very much, Eric.