Unity - how can I change the target size programmatically

June 10, 2014 - 9:09am #1

if you want to change the Size of your Image targets at runtime (programmatically via script code),

and you want Vuforia to take into account the new size and change the tracked "target distance" accordingly,

you need to:

  • use the ImageTarget.SetSize( Vector2 new_size ) API
  • Deactivate the Dataset before changing the size
  • Reactivate the Dataset after changing the size

(see also API reference: 

https://developer.vuforia.com/resources/api/unity/interface_image_target )

To verify this, you could use this simple code (e.g. by attaching it to any Empty GameObject in your Unity scene):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class TargetInfo : MonoBehaviour
{
  void OnGUI()
  {
    StateManager sm = TrackerManager.Instance.GetStateManager();
    if (GUI.Button (new Rect(50,50,200,40), "Size Up"))
    {
      ImageTracker tracker = TrackerManager.Instance.GetTracker<ImageTracker>();
      foreach (DataSet ds in tracker.GetActiveDataSets())
      {
        // Deactivate Dataset before chaging the target size
        tracker.DeactivateDataSet(ds);
        foreach (Trackable trackable in ds.GetTrackables())
        {
          if (trackable is ImageTarget) {
            ImageTarget it = trackable as ImageTarget;
            Vector2 old_size = it.GetSize();
            Vector2 new_size = new Vector2(1.5f*old_size.x, 1.5f*old_size.y);
            it.SetSize(new_size);
        }
      }
      // Reactivate dataset
      tracker.ActivateDataSet(ds);
    }
   }
 
   foreach (TrackableBehaviour tb in sm.GetActiveTrackableBehaviours())
   {
     if (tb is ImageTargetBehaviour)
     {
       ImageTargetBehaviour itb = tb as ImageTargetBehaviour;
       float dist2cam = (itb.transform.position - Camera.main.transform.position).magnitude;
       ImageTarget it = itb.Trackable as ImageTarget;
       Vector2 size = it.GetSize();
       GUI.Box (new Rect(50,100,300,40), it.Name + " - " + size.ToString() +
             "\nDistance to camera: " + dist2cam);
      }
    }
  }
}

 

Topic locked