Skip to content

Instantly share code, notes, and snippets.

@silver-hornet
Last active July 23, 2022 23:32
Show Gist options
  • Save silver-hornet/268f5053db548af6dae51b531a0bcf79 to your computer and use it in GitHub Desktop.
Save silver-hornet/268f5053db548af6dae51b531a0bcf79 to your computer and use it in GitHub Desktop.
Set Screen Boundaries for 2D Player
// This script ensures that the player will not be able to move outside the ranges set by the min and max floats on the x and y axis.
// If you need your screen boundaries to be symetrical, you could have less code below by replacing the four variables with
// only two instead (eg. boundaryX, boundaryY). Then in the Mathf.Clamp statements,
// you would simply use (transform.position.x, -boundaryX, boundaryX) and (transform.position.y, -boundaryY, boundaryY)
using UnityEngine;
public class ScreenBoundaries : MonoBehaviour
{
float minX = -9f;
float maxX = 9f;
float minY = -5f;
float maxY = 5f;
void Update()
{
Vector2 playerPos = new Vector2(transform.position.x, transform.position.y);
playerPos.x = Mathf.Clamp(transform.position.x, minX, maxX);
playerPos.y = Mathf.Clamp(transform.position.y, minY, maxY);
transform.position = playerPos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment