Last active
July 23, 2022 23:32
-
-
Save silver-hornet/268f5053db548af6dae51b531a0bcf79 to your computer and use it in GitHub Desktop.
Set Screen Boundaries for 2D Player
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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