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.