Skip to content

Commit cd79f7f

Browse files
committed
Clamp the position of the player to prevent out of bounds
1 parent ec55018 commit cd79f7f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

Assets/Scripts/Player.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,23 @@ public class Player : MonoBehaviour
3030

3131
private void Update()
3232
{
33+
Vector3 position = this.transform.position;
34+
3335
// Check for input to move the player either left or right
3436
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
35-
this.transform.position += Vector3.left * this.speed * Time.deltaTime;
37+
position.x -= this.speed * Time.deltaTime;
3638
} else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
37-
this.transform.position += Vector3.right * this.speed * Time.deltaTime;
39+
position.x += this.speed * Time.deltaTime;
3840
}
3941

42+
// Clamp the position of the character so they do not go out of bounds
43+
Vector3 leftEdge = Camera.main.ViewportToWorldPoint(Vector3.zero);
44+
Vector3 rightEdge = Camera.main.ViewportToWorldPoint(Vector3.right);
45+
position.x = Mathf.Clamp(position.x, leftEdge.x, rightEdge.x);
46+
47+
// Set the updated position of the player
48+
this.transform.position = position;
49+
4050
// Check for input to shoot a laser
4151
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
4252
Shoot();

0 commit comments

Comments
 (0)