Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

ScreenToWorldPoint Comparison Question

Discussion in 'Scripting' started by CFodder1977, Nov 28, 2018.

  1. CFodder1977

    CFodder1977

    Joined:
    Nov 18, 2018
    Posts:
    7
    My canvas is set to "Screen Space - Camera". "Scale With Screen Size" is the selected UI Scale Mode (with "Match" set to 0.5). On this canvas I have two images, one the child of the other. I am using the following code (a component of the parent image) to drag the child image left to right when the screen is pressed:

    Code (CSharp):
    1.     public void OnDrag (PointerEventData eventData) {
    2.  
    3.         pressPos = Camera.main.ScreenToWorldPoint (eventData.position);
    4.         childImage.transform.position = new Vector3 (pressPos.x, childImage.transform.position.y, 0f);
    5.  
    6.     }
    I am now trying to set it up such that when the child image reaches the edge of it's parent image (parentImage), it goes no further than the edge of the parent. I wish to do this through a script that compares where the player is pressing (pressPos.x) to the edges of the width of "parentImage". The problem that I am running into is that I can't seem to find the relation between "pressPos.x" and the edges of "parentImage."

    The total width of "parentImage" is 600 units. Since it's centered on the screen, I would think that it's edges would be at 300 and -300 on the x axis respectively. I can verify this through

    Code (CSharp):
    1. parentImageWidth = GetComponent<RectTransform> ().rect.width;
    2. float xPosMax = parentImageWidth * 0.5f;
    3. Debug.Log (xPosMax);
    4.  
    which does indeed output 300. However, when I debug "pressPos.x" and hover over the edges of "parentImage" as displayed on screen, the value for "pressPos.x" shows the edges of "parentImage" being at only 4 (vs the 300 that I would expect). I assume this large difference has something to do with how "ScreenToWorldPoint", "Screen Space - Camera", and/or "Scale With Screen Size" all scale the displayed images. However, being pretty new to Unity, I am not sure how to get all the relationships the same such that I can compare the width edges of "parentImage" to "pressPos.x".
     
  2. CFodder1977

    CFodder1977

    Joined:
    Nov 18, 2018
    Posts:
    7
    Never mind. I ended up using GetWorldCorners() to get the corner coordinates of the parent image's RectTransform in World space and then used the x values for the top left and right corner coordinates as reference with my pressPos.x value.
     
    Last edited: Nov 29, 2018