File tree Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Original file line number Diff line number Diff line change @@ -30,13 +30,23 @@ public class Player : MonoBehaviour
30
30
31
31
private void Update ( )
32
32
{
33
+ Vector3 position = this . transform . position ;
34
+
33
35
// Check for input to move the player either left or right
34
36
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 ;
36
38
} 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 ;
38
40
}
39
41
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
+
40
50
// Check for input to shoot a laser
41
51
if ( Input . GetKeyDown ( KeyCode . Space ) || Input . GetMouseButtonDown ( 0 ) ) {
42
52
Shoot ( ) ;
You can’t perform that action at this time.
0 commit comments