Search Unity

2D Screen Position with Canvas Scaler

Discussion in 'Scripting' started by LittleCodingFox, Jul 8, 2015.

  1. LittleCodingFox

    LittleCodingFox

    Joined:
    Jul 2, 2015
    Posts:
    11
    I'm getting the screen position of something to show an object on top. However, because I'm using a Canvas Scaler, this doesn't always work because it doesn't take into account the canvas scaler. With it disabled, this works properly. How can I properly use the canvas scaler with this?

    Code (CSharp):
    1. Vector2 ActualPosition;
    2. RectTransform CanvasTransform = TheCanvas.transform as RectTransform;
    3.  
    4. RectTransformUtility.ScreenPointToLocalPointInRectangle(CanvasTransform, Position + new Vector2(0, CardOverlaySize.y / 2 + 10), TheCanvas.worldCamera, out ActualPosition);
    5.  
    6. Vector3 TransformedPosition = TheCanvas.transform.TransformPoint(ActualPosition);
    7.  
    8. CardOverlayTransform.transform.position = TransformedPosition;
    9.  
    10.  
     
  2. LittleCodingFox

    LittleCodingFox

    Joined:
    Jul 2, 2015
    Posts:
    11
  3. LittleCodingFox

    LittleCodingFox

    Joined:
    Jul 2, 2015
    Posts:
    11
    For anyone who has a problem similar to this where you want to offset something and you have a canvas scaler with reference resolution with match width:


    Code (CSharp):
    1. public void ShowCardOverlay(bool Zooming, Vector2 Position, Vector2 ContainerSize, Card TheCard)
    2. {
    3.     Vector2 ActualPosition;
    4.     RectTransform CanvasTransform = TheCanvas.transform as RectTransform;
    5.     RectTransform CardOverlayTransform = CardOverlay.GetComponent<RectTransform>();
    6.  
    7.     Vector2 CanvasSize = CanvasTransform.sizeDelta;
    8.     Vector2 CanvasSizeScaled = TheCanvasScaler.referenceResolution;
    9.     Vector2 Scale = new Vector2(CanvasSizeScaled.x / CanvasSize.x, Screen.width / CanvasSizeScaled.x);
    10.     Vector2 ContainerSizeScaled = new Vector2(ContainerSize.x * Scale.x, ContainerSize.y * Scale.y);
    11.     Vector2 CardOverlaySizeScaled = new Vector2(CardOverlaySize.x * Scale.x, CardOverlaySize.y * Scale.y);
    12.  
    13.     Vector2 TargetPosition = Position + new Vector2(0, ((ContainerSizeScaled.y + CardOverlaySizeScaled.y) / 2 + 10 * Scale.y));
    14.  
    15.     RectTransformUtility.ScreenPointToLocalPointInRectangle(CanvasTransform, TargetPosition, TheCanvas.worldCamera, out ActualPosition);
    16.  
    17.     Vector3 TransformedPosition = CanvasTransform.TransformPoint(ActualPosition);
    18.  
    19.     CardOverlay.SetActive(true);
    20.     CardOverlayTransform.transform.position = TransformedPosition;
    21. }
    22.  
     
    Last edited: Jul 12, 2015
    GroZZleR likes this.
unityunity