|
1 | | -using System.Collections; |
| 1 | +using System; |
| 2 | +using System.Collections; |
2 | 3 | using System.Collections.Generic; |
3 | 4 | using UnityEngine; |
4 | 5 |
|
5 | 6 | public class Player : MonoBehaviour { |
6 | 7 |
|
7 | 8 | [SerializeField] float moveSpeed = 10f; |
| 9 | + [SerializeField] float padding = 1f; |
8 | 10 |
|
9 | | - // Use this for initialization |
10 | | - void Start () { |
11 | | - |
| 11 | + float xMin; |
| 12 | + float xMax; |
| 13 | + float yMin; |
| 14 | + float yMax; |
| 15 | + |
| 16 | + // Use this for initialization |
| 17 | + void Start () { |
| 18 | + SetUpMoveBoundaries(); |
12 | 19 | } |
13 | | - |
14 | | - // Update is called once per frame |
15 | | - void Update () { |
| 20 | + |
| 21 | + private void SetUpMoveBoundaries() |
| 22 | + { |
| 23 | + Camera gameCamera = Camera.main; |
| 24 | + xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + padding; |
| 25 | + xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - padding; |
| 26 | + yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + padding; |
| 27 | + yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y - padding; |
| 28 | + } |
| 29 | + |
| 30 | + // Update is called once per frame |
| 31 | + void Update () { |
16 | 32 | Move(); |
17 | 33 | } |
18 | 34 |
|
19 | 35 | private void Move() |
20 | 36 | { |
21 | 37 | var deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed; |
22 | | - var newXPos = transform.position.x + deltaX; |
23 | 38 | var deltaY = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed; |
24 | | - var newYPos = transform.position.y + deltaY; |
| 39 | + |
| 40 | + var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax); |
| 41 | + var newYPos = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax); |
25 | 42 | transform.position = new Vector2(newXPos, newYPos); |
26 | 43 | } |
27 | 44 |
|
|
0 commit comments