Using Camera.main.ViewportToWorldPoint to limit player movement in the Y direction
I used Camera.main.ViewportToWorldPoint to restrict player movement to the leftmost and rightmost sections of the screen. Since I set up my ship to move diagonally, I'm also trying to stop my player from going out of bounds in the Y direction. I tried replicating the code where I limited movement in the X direction but it hasn't done anything.
This is what I have so far:
public class PlayerController : MonoBehaviour {
// Player's movement speed
public float moveSpeed = 2.0f;
float xmin, xmax, ymin, ymax;
void Start() {
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance));
Vector3 bottomMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
Vector3 topMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, distance));
//Add a padding to the leftmost and rightmost borders so that the Sprite's renderer is used instead of padding through hardcoded values
xmin = leftmost.x + gameObject.GetComponent<SpriteRenderer>().bounds.size.x / 2;
xmax = rightmost.x - gameObject.GetComponent<SpriteRenderer>().bounds.size.x / 2;
ymin = bottomMost.y;
ymax = topMost.y;
}
Comment