- Home /
Keeping UI Element To Game Object When Camera Moves
Some background and my problem:
I am making a tower defense game in 2d, and when I click on a tower I have a UI element named "towerPanel" be set to active.
However, when I move the camera, the UI element moves along with the camera as if it were stuck on the lens. I would like the UI element to stick to the tower.
The "towerPanel" is in a canvas, and the canvas is set to "screen space - overlay"
Here is what I am doing:
When clicking on a tower, I get the screen point:
Vector3 screenpos = Camera.main.WorldToScreenPoint(transform.localPosition);
I pass this screenpos to a function that does the following:
private Vector3 screenposition_base_tower_panel;
public void MoveTowerPanel(Vector3 screenPosition_tile)
{
screenposition_base_tower_panel.x = screenpos.x - 350;
screenposition_base_tower_panel.y = screenpos.y + 185;
towerPanel.SetActive(true);
towerPanel.transform.SetPositionAndRotation(screenposition_base_tower_panel, Quaternion.identity);
}
and the Update function looks like this:
void Update()
{
if (towerPanel.activeSelf == true)
{
towerPanel.transform.position = screenposition_base_tower_panel;
}
}
and clearly after all of this, the UI element stays to the camera.
Any and all help is appreciated with this.
Answer by tormentoarmagedoom · Feb 02, 2020 at 06:13 PM
Hey.
WOWOWO, you are overthinking the problem.
Just need to configure the Render mode of the canvas via inspector, to Worlld position. read the manual. https://docs.unity3d.com/560/Documentation/Manual/class-Canvas.html
World Space This mode renders the UI as if it were a plane object in the scene. Unlike Screen Space - Camera mode, however, the plane need not face the camera and can be oriented however you like. The size of the Canvas can be set using its Rect Transform but its onscreen size will depend on the viewing angle and distance of the camera. Other scene objects can pass behind, through or in front of the Canvas.
You will need that each tower have its own canvas, or make 1 only canvas that moves to tower position when you click it.
You may very, very well be right. I'm new to Unity (obviously), and just jumped right in.
I'll spend the time to read the manual and heed your advice!
Answer by shaunrdoty · Feb 02, 2020 at 08:12 PM
So.... thank you tormentoarmagedoom. I was DEFINITELY overthinking this.
I got it to work :)
Your answer
Follow this Question
Related Questions
Cinemachine glitch 0 Answers
Unity 2D Fighting Game Camera 0 Answers
Make the camera follow the players 1 Answer
Why Scroll Rect not working at all? 1 Answer
Is it good idea to implement camera drag with UI drag event? 2 Answers