So I have the following problem: I have a world space canvas following a arrow that moves around the screen. The canvas itself is just a child of the arrow. The problem is that sometimes when the arrow is pointing to something on the edge of the screen parts of the canvas go off screen. I want to write some code that keeps the entire canvas inside the viewport at all times. I found a solution online but this keeps the pivot point of the object inside the camera bounds and not the whole object. I simply cant figure out how to keep the whole object inside the camera bounds. Here is the code I have :

void LateUpdate()
  transform.rotation = rotation;// This simply keeps the objects original rotation independant from the parent
  Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
  pos.x = Mathf.Clamp01(pos.x);
  pos.y = Mathf.Clamp01(pos.y);
  transform.position = Camera.main.ViewportToWorldPoint(pos);

Edit: this is how it looks with the first answer: The gif is too large to upload so here is a link to it.


Something like this should solve the problem:

var scaleViewport = Camera.main.WorldToViewportPoint(transform.lossyScale.x, transform.lossyScale.y, transform.position.z);
var halfXScale = scaleViewport.x /2;
var halfYScale = scaleViewport.y /2;

pos.x = Mathf.Clamp(pos.x, 0 + halfXScale, 1 - halfXScale);
pos.y = Mathf.Clamp(pos.y, 0 + halfYScale, 1 - halfYScale);

If the parent has the scale (1,1,1) you can use transform.localScale instead of transform.lossyScale.

This code limits the area of possible movement by the the size of object. So when you come to limited boundaries and the object overflows from them, it will still be inside the actual viewport.

| improve this answer | |
  • \$\begingroup\$ I'm either not implementing your code right or something else is wrong because this just put the canvas in the center of the screen. \$\endgroup\$ – Uri Popov Aug 1 '16 at 10:49
  • \$\begingroup\$ @UriPopov I forgot to convert the scale to viewport, is it working now? \$\endgroup\$ – S. Tarık Çetin Aug 1 '16 at 10:53
  • \$\begingroup\$ well It does work now in a way but not as I expected. I will make a edit with a gif hold on. \$\endgroup\$ – Uri Popov Aug 1 '16 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.