Skip to content

Instantly share code, notes, and snippets.

@AradiPatrik
Created April 13, 2016 23:04
Show Gist options
  • Save AradiPatrik/1ec750bb15a6338f099b7397cadac697 to your computer and use it in GitHub Desktop.
Save AradiPatrik/1ec750bb15a6338f099b7397cadac697 to your computer and use it in GitHub Desktop.
public class YRestriction : MonoBehaviour{
public float padding = 1f;
private float ymin;
private float ymax;
//here we set our top and bottom barriers
void Start(){
float distance = transform.position.z - Camera.main.transform.position.z; //not really necessary in 2D, but good habbit
//take the bottom-middle, to-middle point of our camera and get it's world coordinates
Vector3 buttomBarrier = Camera.main.ViewportToWorldPoint(new Vector3(0.5, 0, distance));
Vector3 topBarrier = Camera.main.ViewportToWorldPoint(new Vector3(0.5, 0, distance));
ymax = bottomBarrier.y + padding;
ymin = topBarrier.y - padding;
}
void Update(){
float newY = Mathf.Clamp(transform.position.y, ymin, ymax);
transform.position = new Vector3(newy, transform.position.y, transform.position.z);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment