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:
public void OnDrag (PointerEventData eventData) {
pressPos = Camera.main.ScreenToWorldPoint (eventData.position);
childImage.transform.position = new Vector3 (pressPos.x, childImage.transform.position.y, 0f);
}
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
parentImageWidth = GetComponent<RectTransform> ().rect.width;
float xPosMax = parentImageWidth * 0.5f;
Debug.Log (xPosMax);
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”.