MKS
MKS

Reputation: 786

Unity3D Vuforia Camera Position in Real World Unit

I am using Vuforia and Unity3D to develop an application. For this, I need to get the camera position (x,y,z) in real world unit from an image target while tracking the image with a mobile phone. I was wondering if it is possible to get such position information in Vuforia . if Yes, any sample code would be highly appreciated.

Upvotes: 1

Views: 3901

Answers (1)

MNM
MNM

Reputation: 2743

Try something like this.

public class ExampleClass : MonoBehaviour {
public Transform target;
Camera camera;

void Start() {
    camera = GetComponent<Camera>();
}

void Update() {
    Vector3 screenPos = camera.WorldToScreenPoint(target.position);
    Debug.Log("target is " + screenPos.x + " pixels from the left");
}
}

What this does is Transforms position from world space into screen space.

Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.

May not be exactly what you want but its a starting point.

EDIT: This returns world Space not local space so this should be exactly what you want

public class ExampleClass : MonoBehaviour {
public GameObject someObject;
public Vector3 thePosition;

void Start() {
    // Instantiate an object to the right of the current object
    thePosition = transform.TransformPoint(Vector3.right * 2);
    Instantiate(someObject, thePosition, someObject.transform.rotation);
}
}

Note that the returned position is affected by scale. Use Transform.TransformDirection if you are dealing with direction vectors. You can perform the opposite conversion, from world to local space using Transform.InverseTransformPoint.

Upvotes: 2

Related Questions