ScreenToWorldPoint with CanvasScaler and cam childed to a GO

Hi everyone,

I’m trying to achieve an effect where particles will head towards a UI button.

So I’m instantiating a Particle System (at player’s position), and a Particles Force Field which I want to position such as it matches my UI button’s apparent position.

Of course I will use Camera.ScreenToWorldPoint to calculate its position, but there are two more difficulties :

  • there’s a Canvas Scaler on my Screen Space-Overlay Canvas ; it is set to Scale With Screen Size

  • for some reason, my Camera is childed to another GO, which can move and rotate. Not sure if this has an impact or not…

I can’t have this to work.

My Force Field keeps being instantiated at the exact camera’s position.

Can someone please save my day ?

Here’s part of my code :

    public Camera cam;
    public Transform uiButton;
    public GameObject psff; // the prefab with my force field
    //
    void CreateForceField () 
    {
         RectTransform rect = uiButton.GetComponent< RectTransform>();
         Vector3 point = cam.ScreenToWorldPoint(rect.transform.position);
         Instantiate(psff, point, Quaternion.identity);
    }

Note : I’m using a RectTransform because I read somewhere that it was the right way for an anchored UI element (my button is anchored in the left-top corner of the screen).

Thanx in advance.

Finally solved my problem and there was nothing difficult.
The error comes at my Vector3 point declaration, which should be a new Vector3().

The right way to do this is :

RectTransform btn = uiButton.GetComponent< RectTransform>();
Vector3 point = cam.ScreenToWorldPoint(new Vector3(btn.rect.center.x, btn.rect.center.y, 1f));

The last param (a float) is the distance to camera. 1f is the better value for me but it depends on the effect we want to achieve.