Skip to content

Commit 424b70d

Browse files
committed
5 ViewPortToWorldPoint()
1 parent 7607a71 commit 424b70d

File tree

2 files changed

+39
-10
lines changed

2 files changed

+39
-10
lines changed

Laser Defender/Assets/Scripts/Player.cs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,44 @@
1-
using System.Collections;
1+
using System;
2+
using System.Collections;
23
using System.Collections.Generic;
34
using UnityEngine;
45

56
public class Player : MonoBehaviour {
67

78
[SerializeField] float moveSpeed = 10f;
9+
[SerializeField] float padding = 1f;
810

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();
1219
}
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 () {
1632
Move();
1733
}
1834

1935
private void Move()
2036
{
2137
var deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
22-
var newXPos = transform.position.x + deltaX;
2338
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);
2542
transform.position = new Vector2(newXPos, newYPos);
2643
}
2744

README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,16 @@ Create our project and be happy with the aspect ratio, sizes and proportions.
5959
3. Also add vertical movement for the player.
6060

6161
**After watching (learning outcomes)…**
62-
Move your player ship in a way which is frame rate independent.
62+
Move your player ship in a way which is frame rate independent.
63+
64+
65+
### 5 ViewPortToWorldPoint() ###
66+
67+
**In this video (objectives)…**
68+
69+
1. Construct our gameplay boundaries using the method ViewPortToWorldPoint().
70+
2. Clamp our horizontal and vertical movement based upon our boundaries.
71+
3. Add padding so that the player does not go off screen.
72+
73+
**After watching (learning outcomes)…**
74+
Limit your player's ship movement based upon relative camera space.

0 commit comments

Comments
 (0)