- Home /
UI on WorldToScreenPoint doesn't work on certain camera angles
I have a scene with a plane in Unity. I am using the following code:
Vector3[] vertices = new Vector3[choices.Count];
Vector3 center = Camera.main.WorldToScreenPoint(targetPos);
float angle = Mathf.PI * 2 / vertices.Length;
for (int i = 0; i < vertices.Length; ++i) {
float verticeAngle = i * angle;
vertices[i] = center + 100 * new Vector3(Mathf.Sin(verticeAngle), Mathf.Cos(verticeAngle), center.z);
}
for (int i = 0; i < vertices.Length; ++i) {
var btn = Instantiate(prefabChoiceButton) as GameObject;
btn.transform.SetParent(canvas.transform, false);
btn.GetComponent<RectTransform>().position = vertices[i];
}
where targetPos comes from:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000, (1 << 8) | (1 << 10))) {
// here I call targetPos with hit.point
}
The buttons showed fine so far, but I changed the camera angle and now they don't show up (they show up when I get to the old camera angle). In both angles I can clearly see the plane, they are not far away from each other.
Working camera settings:
Position (0, 5, -6)
Rotation (60, 0, 0)
Field of view 60
Angle not working:
Position (0, 10, -6)
Rotation (60, 0, 0)
Field of view 60
What is even weirder is that sometimes even if I can't see the buttons, clicking randomly sometimes triggers the click event on them.
Answer by thsuditu · May 29, 2021 at 04:33 PM
I found the problem here:
vertices[i] = center + 100 * new Vector3(Mathf.Sin(verticeAngle), Mathf.Cos(verticeAngle), center.z);
That 100 multiplier was not intended for z axis, shouldn't be moving it on z. That gets it out of the view somehow when the z of the button is > 1000;
Your answer
Follow this Question
Related Questions
How can I accurately convert a Game Object's position to a sub Canvas/Rect screen position? 0 Answers
WorldToScreenPoint UI element showing up twice 1 Answer
UI - Best method for Scene UI elements 1 Answer
Problem with a direction indicator for an FPS game 2 Answers
Whats an efficient method for drawing hundreds of Health Bars etc. over units for an RTS? 2 Answers