Hi,
I’m using Vuforia to get an texture to a plane. I want to get the texture in front of camera and keep the ratio and remove the offset. But somehow I cannot get it scaled correctly to the screen.
I think i’m looking too long at the code.
float distance = Vector3.Distance(Camera.main.transform.position, gameObject.transform.position);
float height = Mathf.Tan(0.5f * Camera.main.fieldOfView * Mathf.Deg2Rad) * distance;
float width = height * ((float)mTextureInfo.imageSize.x/(float)mTextureInfo.imageSize.y); // x and y are with and height
gameObject.transform.localScale = new Vector3(-width , 1.0f,height);
Your code is fine, just needs a little fix, multiply height and width by two (I think because in Orthographic mode, the Camera size is 1/2 of the vertical size) and divide the result height and width by 10 because the plane with scale 1 by 1 is 10 by 10 units.
float distance = Vector3.Distance(Camera.main.transform.position, gameObject.transform.position);
float height = 2.0f * Mathf.Tan(0.5f * Camera.main.fieldOfView * Mathf.Deg2Rad) * distance;
float width = height * Screen.width / Screen.height;
gameObject.transform.localScale = new Vector3(width / 10f, 1.0f, height / 10f);
The final answer by @IbraheemTuffaha was accurate for a perspective camera, but too dependent on extraneous variables and having everything attached to the camera.
Transform scaledImage = gameObject.transform; // not required, but simplifies code
// When attaching to a different object, change this variable to reconnect
float dst = Vector3.Distance(Camera.main.transform.position, scaledImage.position);
float fov = 2f * Mathf.Atan(Mathf.Tan(Camera.main.fieldOfView * Mathf.Deg2Rad / 2f)
* Camera.main.aspect) * Mathf.Rad2Deg; // Horizonal Field of View
float w1 = Mathf.Tan(0.5f * fov * Mathf.Deg2Rad) * dst / 5f;
float h1 = w1 * scaledImage.GetComponent<Renderer>().material.mainTexture.height
/ scaledImage.GetComponent<Renderer>().material.mainTexture.width;
float h2 = Mathf.Tan(0.5f * Camera.main.fieldOfView * Mathf.Deg2Rad) * dst / 5f;
float w2 = h2 * scaledImage.GetComponent<Renderer>().material.mainTexture.width
/ scaledImage.GetComponent<Renderer>().material.mainTexture.height;
float width = Mathf.Max(w1, w2);
float height = Mathf.Max(h1, h2);
scaledImage.localScale = new Vector3(width, scaledImage.localScale.y, height);