How to limit Gameobject within the camera view correctly

Updated on July 8, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on July 7, 2017

i made this script to limit the Gameobject within the View of the camera

 

void Update()
  {
      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);
   }

 

this piece of code is giving me result like this(image 1)

(Image 1)

whenever i drag the gameobject near the screen end the gameobject is limited but it partially crosses the camera view but i dont really want it to be like this

(Image 2)

 

but instead i want the gameobject to stop before camera view ends just like the above image(image 2), how can i do that please help me with this

  • Liked by
Reply
1 on July 7, 2017

You need to take into account the object’s width / height. Use width / 2 and height / 2.

on July 8, 2017

Thanx for replying. . . .

Can u please show an example ??, i didnt really understand what to do!!

Show more replies
  • Liked by
Reply
Cancel