0
\$\begingroup\$

I'm trying to set an Image gameobject's transform.position. My canvas is "screen space - camera" because I needed to use a line renderer.

However, when I set the position, say to new Vector3(-320, -240); the object (in play mode) gets positioned at -16266.44, y: -15360, way off-screen.

I've tried to reset the localPosition and such based on some other answers but it doesn't help. What else could be translating my pixel coords?

var go = Instantiate(HexTilePrefab, this.transform);
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
go.transform.position = new Vector3(screenX, screenY);
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

The trick you're missing is converting between screen coordinates, which are generally measured in device pixels from the bottom left corner, and your UI's layout units, which you can configure in the editor to your liking.

Because the latter are configurable, the exact details will depend on how you've set up your UI object hierarchy and anchoring settings. The example below works with one setup, where the parent spans the whole canvas and the child is anchored to the bottom-left. If that doesn't match your setup, edit your question to include details of your arrangement and we can recommend how to compensate.

// For UI positioning, we want to work with the RectTransforms of our object
// and its containing canvas, rather than Transforms which don't know about UI.
var canvas = (RectTransform)GetComponentInParent<Canvas>().transform;
var rectTransform = (RectTransform)go.transform;

// Compute a scale conversion between the screen's pixel size
// and the canvas's internal dimensions.
Vector2 scale = new Vector2(
     canvas.rect.width / Screen.width,
     canvas.rect.height / Screen.height
);

// If your anchors are set to the bottom-left, you can use this directly.
// Otherwise, offset by a suitable multiple of the canvas width or height.
rectTransform.anchoredPosition = Vector2.Scale(
    Input.mousePosition, 
    scale
);
\$\endgroup\$
0
\$\begingroup\$

In a 2D game you can match the plane of the objects and the canvas:

  • Set Camera > Transform.z = -10
  • Set Canvas > Plane Distance = 10
  • Set UI element transform.position = object.transform.position;
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .