diff options
author | Jakob Stendahl <JakobS1n@users.noreply.github.com> | 2017-10-14 23:17:09 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-10-14 23:17:09 +0200 |
commit | 8b2c937959c99ab2dfbc3eaf9dc5b9c18cf73371 (patch) | |
tree | b775b07054de58f83cd9df41bf43e61b3facfad1 /td/Assets/Scripts | |
parent | 76cf99ade6530bdad81088295fb4cf73f5c5b118 (diff) | |
parent | abe835d1112e4804ce63b7d2fa85f8bd76e3c237 (diff) | |
download | TD-8b2c937959c99ab2dfbc3eaf9dc5b9c18cf73371.tar.gz TD-8b2c937959c99ab2dfbc3eaf9dc5b9c18cf73371.zip |
Merge pull request #4 from JakobS1n/GUI
Gui
Diffstat (limited to 'td/Assets/Scripts')
22 files changed, 908 insertions, 236 deletions
diff --git a/td/Assets/Scripts/Enemy.cs b/td/Assets/Scripts/Enemy.cs index 7273370..4d15b64 100644 --- a/td/Assets/Scripts/Enemy.cs +++ b/td/Assets/Scripts/Enemy.cs @@ -1,38 +1,39 @@ -using System.Collections; -using System.Collections.Generic; +using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { + /* This is a general class that contains an enemy, + * Currently it follows the pathway, and dies when reacing the end */ - public float speed; - public float initialHp; - public Transform pathWay; + [Header("Attributes")] + public float Speed; // Speed multiplier + public int InitialHp; // HealthPoints + public int Damage; + public List<Vector3> Waypoints; // Pathway waypoints, should be set by the spawner + + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set when instantiating - List<Vector3> waypoints = new List<Vector3>(); - Vector3 waypointPos; - int waypointNum = -1; // Using minus one so that first addition returns 0, first element in array - - void Start () { - foreach (Transform child in pathWay) { - waypoints.Add (child.position); - } - } + private Vector3 _waypointPos; // Current waypoint position + private int _waypointNum = -1; // Using minus one so that first addition returns 0, first element in array void Update () { - updateWaypoint (); + if (Player.GameIsPaused()) { return; } // This ensures that the game stays paused + + if ( (transform.position == _waypointPos && _waypointNum + 1 < Waypoints.Count) || _waypointNum == -1) { + _waypointNum++; + _waypointPos = new Vector3 (Waypoints [_waypointNum].x, 0.483f, Waypoints [_waypointNum].z); + } - float transformStep = speed * Time.deltaTime; - transform.position = Vector3.MoveTowards (transform.position, waypointPos, transformStep); + float transformStep = Speed * Time.deltaTime; + transform.position = Vector3.MoveTowards (transform.position, _waypointPos, transformStep); - if (waypointNum == waypoints.Count - 1) { + // Selfdestruct if object reached the end + if (_waypointNum + 1 >= Waypoints.Count) { + WaveSpawner.EnemiesAlive--; + Player.DecreaseHealth (Damage); Destroy (gameObject); - } - } - - void updateWaypoint() { - if ( (transform.position == waypointPos && waypointNum < waypoints.Count - 1) || waypointNum == -1) { - waypointNum++; - waypointPos = new Vector3 (waypoints [waypointNum].x, 0.604f, waypoints [waypointNum].z); + return; } } diff --git a/td/Assets/Scripts/EnemySpawner.cs b/td/Assets/Scripts/EnemySpawner.cs deleted file mode 100644 index eb0dd43..0000000 --- a/td/Assets/Scripts/EnemySpawner.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - -public class EnemySpawner : MonoBehaviour { - - public Enemy enemyPrefab; - public Transform pathWay; - public Transform gameWorld; - - int wave; - int next = 1; - int n = 0; - - void Update () { - n++; - - if (n == next) { - n = 0; - next = (int)Random.Range (50, 400); - - Enemy newEnemy = Instantiate (enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity, gameWorld); - newEnemy.GetComponent <Enemy> ().pathWay = pathWay; - newEnemy.GetComponent <Enemy> ().speed = Random.Range (0.3f, 1.2f); - } - } -} diff --git a/td/Assets/Scripts/PinchZoom.cs b/td/Assets/Scripts/PinchZoom.cs deleted file mode 100644 index b3e6d22..0000000 --- a/td/Assets/Scripts/PinchZoom.cs +++ /dev/null @@ -1,144 +0,0 @@ -using UnityEngine; -using System.Collections; - -public class PinchZoom : MonoBehaviour -{ - /* Dette vil bare funke for et ortografisk kamera! */ - - private static readonly float PanSpeed = 20f; - private static readonly float ZoomSpeedTouch = 0.1f; - private static readonly float ZoomSpeedMouse = .5f; - - public static readonly float[] BoundsX = new float[]{-10f, 5f}; - public static readonly float[] BoundsZ = new float[]{-18f, -4f}; - public static readonly float[] ZoomBounds = new float[]{10f, 85f}; - - private Camera cam; - - private bool panActive; - private Vector3 lastPanPosition; - private int panFingerId; // Touch mode only - - private bool zoomActive; - private Vector2[] lastZoomPositions; // Touch mode only - - void Awake() { - cam = GetComponent<Camera>(); - - #if UNITY_ANDROID || UNITY_IOS - cam.fieldOfView = 60f; - #endif - } - - void Update() { - // If there's an open menu, or the clicker is being pressed, ignore the touch. - /* - if (GameManager.Instance.MenuManager.HasOpenMenu || GameManager.Instance.BitSpawnManager.IsSpawningBits) { - return; - }*/ - - if (Input.touchSupported && Application.platform != RuntimePlatform.WebGLPlayer) { - HandleTouch(); - } else { - HandleMouse(); - } - } - - void HandleTouch() { - switch(Input.touchCount) { - - case 1: // Panning - zoomActive = false; - - // If the touch began, capture its position and its finger ID. - // Otherwise, if the finger ID of the touch doesn't match, skip it. - Touch touch = Input.GetTouch(0); - if (touch.phase == TouchPhase.Began) { - lastPanPosition = touch.position; - panFingerId = touch.fingerId; - panActive = true; - } else if (touch.fingerId == panFingerId && touch.phase == TouchPhase.Moved) { - PanCamera(touch.position); - } - break; - - case 2: // Zooming - panActive = false; - - Vector2[] newPositions = new Vector2[]{Input.GetTouch(0).position, Input.GetTouch(1).position}; - if (!zoomActive) { - lastZoomPositions = newPositions; - zoomActive = true; - } else { - // Zoom based on the distance between the new positions compared to the - // distance between the previous positions. - float newDistance = Vector2.Distance(newPositions[0], newPositions[1]); - float oldDistance = Vector2.Distance(lastZoomPositions[0], lastZoomPositions[1]); - float offset = newDistance - oldDistance; - - ZoomCamera(offset, ZoomSpeedTouch); - - lastZoomPositions = newPositions; - } - break; - - default: - panActive = false; - zoomActive = false; - break; - } - } - - void HandleMouse() { - // On mouse down, capture it's position. - // On mouse up, disable panning. - // If there is no mouse being pressed, do nothing. - if (Input.GetMouseButtonDown(0)) { - panActive = true; - lastPanPosition = Input.mousePosition; - } else if (Input.GetMouseButtonUp(0)) { - panActive = false; - } else if (Input.GetMouseButton(0)) { - PanCamera(Input.mousePosition); - } - - // Check for scrolling to zoom the camera - float scroll = Input.GetAxis("Mouse ScrollWheel"); - zoomActive = true; - ZoomCamera(scroll, ZoomSpeedMouse); - zoomActive = false; - } - - void PanCamera(Vector3 newPanPosition) { - if (!panActive) { - return; - } - - // Translate the camera position based on the new input position - Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition); - Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed); - transform.Translate(move, Space.World); - ClampToBounds(); - - lastPanPosition = newPanPosition; - } - - void ZoomCamera(float offset, float speed) { - if (!zoomActive || offset == 0) { - return; - } - - cam.fieldOfView = Mathf.Clamp(cam.fieldOfView - (offset * speed), ZoomBounds[0], ZoomBounds[1]); - } - - void ClampToBounds() { - Vector3 pos = transform.position; - pos.x = Mathf.Clamp(transform.position.x, BoundsX[0], BoundsX[1]); - pos.z = Mathf.Clamp(transform.position.z, BoundsZ[0], BoundsZ[1]); - - transform.position = pos; - } - - - -}
\ No newline at end of file diff --git a/td/Assets/Scripts/Projectile.cs b/td/Assets/Scripts/Projectile.cs new file mode 100644 index 0000000..3b02763 --- /dev/null +++ b/td/Assets/Scripts/Projectile.cs @@ -0,0 +1,43 @@ +using UnityEngine; + +public class Projectile : MonoBehaviour { + + public float Speed = 70f; + public int PointsPerHit; + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set when instantiating + private Transform _target; + + public void Seek(Transform target) { + _target = target; + } + + + void Update () { + + if (_target == null) { + Destroy (gameObject); + return; + } + + Vector3 direction = _target.position - transform.position; + float distanceThisFrame = Speed * Time.deltaTime; + + if (direction.magnitude <= distanceThisFrame) { + HitTarget (); + return; + } + + transform.Translate (direction.normalized * distanceThisFrame, Space.World); + + + } + + void HitTarget() { + WaveSpawner.EnemiesAlive--; + Player.ScoreAdd (PointsPerHit); + Destroy (_target.gameObject); + Destroy (gameObject); + } + +} diff --git a/td/Assets/Scripts/EnemySpawner.cs.meta b/td/Assets/Scripts/Projectile.cs.meta index 3fe504e..a95b993 100644 --- a/td/Assets/Scripts/EnemySpawner.cs.meta +++ b/td/Assets/Scripts/Projectile.cs.meta @@ -1,6 +1,6 @@ fileFormatVersion: 2 -guid: 3e57c25f0405b40cab5c30b2c92671ae -timeCreated: 1506633566 +guid: 4a1928566183240ea8566b659c4b3d5f +timeCreated: 1507300755 licenseType: Free MonoImporter: serializedVersion: 2 diff --git a/td/Assets/Scripts/cameraHandler.cs b/td/Assets/Scripts/cameraHandler.cs index a4aa660..7c2f75f 100644 --- a/td/Assets/Scripts/cameraHandler.cs +++ b/td/Assets/Scripts/cameraHandler.cs @@ -1,8 +1,7 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; +using UnityEngine; -public class cameraHandler : MonoBehaviour { +public class CameraHandler : MonoBehaviour { + // TODO Fiks panning, ser idiotisk ut nå så jeg har satt panSpeed til 0. (I editoren) public float PanSpeed = 20f; public float ZoomSpeedTouch = 0.1f; @@ -12,21 +11,24 @@ public class cameraHandler : MonoBehaviour { public static readonly float[] BoundsY = new float[]{-5f, 10f}; public static readonly float[] BoundsZ = new float[]{-8f, 8f}; public static readonly float[] ZoomBounds = new float[]{1f, 5f}; + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set in designer - private Camera cam; + private Camera _cam; - private bool panActive; - private Vector3 lastPanPosition; - private int panFingerId; // Touch mode only + private bool _panActive; + private Vector3 _lastPanPosition; + private int _panFingerId; // Touch mode only - private bool zoomActive; - private Vector2[] lastZoomPositions; // Touch mode only + private bool _zoomActive; + private Vector2[] _lastZoomPositions; // Touch mode only void Awake() { - cam = GetComponent<Camera>(); + _cam = GetComponent<Camera>(); } void Update() { + if (Player.GameIsPaused()) { return; } // If there's an open menu, or the clicker is being pressed, ignore the touch. /* if (GameManager.Instance.MenuManager.HasOpenMenu || GameManager.Instance.BitSpawnManager.IsSpawningBits) { @@ -36,52 +38,52 @@ public class cameraHandler : MonoBehaviour { if (Input.touchSupported && Application.platform != RuntimePlatform.WebGLPlayer) { HandleTouch(); } else { - //HandleMouse(); + HandleMouse(); } - HandleTouch (); + //HandleTouch (); } void HandleTouch() { switch(Input.touchCount) { case 1: // Panning - zoomActive = false; + _zoomActive = false; // If the touch began, capture its position and its finger ID. // Otherwise, if the finger ID of the touch doesn't match, skip it. Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { - lastPanPosition = touch.position; - panFingerId = touch.fingerId; - panActive = true; - } else if (touch.fingerId == panFingerId && touch.phase == TouchPhase.Moved) { + _lastPanPosition = touch.position; + _panFingerId = touch.fingerId; + _panActive = true; + } else if (touch.fingerId == _panFingerId && touch.phase == TouchPhase.Moved) { PanCamera(touch.position); } break; case 2: // Zooming - panActive = false; + _panActive = false; Vector2[] newPositions = new Vector2[]{Input.GetTouch(0).position, Input.GetTouch(1).position}; - if (!zoomActive) { - lastZoomPositions = newPositions; - zoomActive = true; + if (!_zoomActive) { + _lastZoomPositions = newPositions; + _zoomActive = true; } else { // Zoom based on the distance between the new positions compared to the // distance between the previous positions. float newDistance = Vector2.Distance(newPositions[0], newPositions[1]); - float oldDistance = Vector2.Distance(lastZoomPositions[0], lastZoomPositions[1]); + float oldDistance = Vector2.Distance(_lastZoomPositions[0], _lastZoomPositions[1]); float offset = newDistance - oldDistance; ZoomCamera(offset, ZoomSpeedTouch); - lastZoomPositions = newPositions; + _lastZoomPositions = newPositions; } break; default: - panActive = false; - zoomActive = false; + _panActive = false; + _zoomActive = false; break; } } @@ -91,41 +93,41 @@ public class cameraHandler : MonoBehaviour { // On mouse up, disable panning. // If there is no mouse being pressed, do nothing. if (Input.GetMouseButtonDown(0)) { - panActive = true; - lastPanPosition = Input.mousePosition; + _panActive = true; + _lastPanPosition = Input.mousePosition; } else if (Input.GetMouseButtonUp(0)) { - panActive = false; + _panActive = false; } else if (Input.GetMouseButton(0)) { PanCamera(Input.mousePosition); } // Check for scrolling to zoom the camera float scroll = Input.GetAxis("Mouse ScrollWheel"); - zoomActive = true; + _zoomActive = true; ZoomCamera(scroll, ZoomSpeedMouse); - zoomActive = false; + _zoomActive = false; } void ZoomCamera(float offset, float speed) { - if (!zoomActive || offset == 0) { + if (!_zoomActive || offset == 0) { return; } - cam.orthographicSize = Mathf.Clamp(cam.orthographicSize - (offset * speed), ZoomBounds[0], ZoomBounds[1]); + _cam.orthographicSize = Mathf.Clamp(_cam.orthographicSize - (offset * speed), ZoomBounds[0], ZoomBounds[1]); } void PanCamera(Vector3 newPanPosition) { - if (!panActive) { + if (!_panActive) { return; } // Translate the camera position based on the new input position - Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition); + Vector3 offset = _cam.ScreenToViewportPoint(_lastPanPosition - newPanPosition); Vector3 move = new Vector3(offset.x * PanSpeed, offset.y * PanSpeed, 0f); transform.Translate(move, Space.World); ClampToBounds(); - lastPanPosition = newPanPosition; + _lastPanPosition = newPanPosition; } void ClampToBounds() { diff --git a/td/Assets/Scripts/castle.cs b/td/Assets/Scripts/castle.cs new file mode 100644 index 0000000..5c8835c --- /dev/null +++ b/td/Assets/Scripts/castle.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class Castle : MonoBehaviour { + + private void Update () { + //CheckThing(); + } + + private void CheckThing() { + GameObject[] enemies = GameObject.FindGameObjectsWithTag ("enemy"); + + foreach (var enemy in enemies) { + var distanceToEnemy = Vector3.Distance (transform.position, enemy.transform.position); + if (distanceToEnemy <= 0) { + Debug.Log("INTRUDER!"); + } + } + } + + +} diff --git a/td/Assets/Scripts/PinchZoom.cs.meta b/td/Assets/Scripts/castle.cs.meta index 6303bbc..246ac0b 100644 --- a/td/Assets/Scripts/PinchZoom.cs.meta +++ b/td/Assets/Scripts/castle.cs.meta @@ -1,6 +1,6 @@ fileFormatVersion: 2 -guid: 3770bdc9b6c954c1782333bdf04c01c6 -timeCreated: 1506636352 +guid: c6004dcebebd0498389086d43a3bd6fa +timeCreated: 1507302323 licenseType: Free MonoImporter: serializedVersion: 2 diff --git a/td/Assets/Scripts/developerMode.cs b/td/Assets/Scripts/developerMode.cs new file mode 100644 index 0000000..a71d4c7 --- /dev/null +++ b/td/Assets/Scripts/developerMode.cs @@ -0,0 +1,76 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine.UI; +using UnityEngine; + +public class DeveloperMode : MonoBehaviour { + + public string Output = ""; + public string Stack = ""; + public bool CheatsAllowed; + + GameObject _pnlCanvas; + GameObject _pnlCheats; + Button _btnToggleCheats; + Text _lblConsoleLog; + + bool _developerModeActive; + bool _cheatMenuOpen; + + void Start () { + /* Panels */ + _pnlCanvas = this.gameObject.transform.GetChild (0).gameObject; + _pnlCheats = _pnlCanvas.transform.Find ("cheatMenu").gameObject; + /* Buttons */ + /* Button handlers */ + /* Lablels */ + _lblConsoleLog = _pnlCanvas.transform.Find ("consoleLog").gameObject.GetComponent <Text>(); + /* Do setup */ + _lblConsoleLog.text = ""; + + if (CheatsAllowed) { + _btnToggleCheats = _pnlCanvas.transform.Find ("toggleCheats").gameObject.GetComponent <Button> (); + if (_btnToggleCheats != null) { _btnToggleCheats.onClick.AddListener (btnToggleCheatsHandler); } + _cheatMenuOpen = false; + } else { + _pnlCanvas.transform.Find ("toggleCheats").gameObject.SetActive (false); + } + _pnlCheats.SetActive (false); + } + + void Update () { + + if (PlayerPrefs.HasKey ("developerMode")) { + if (PlayerPrefs.GetInt ("developerMode") == 1) { _developerModeActive = true; } + else { _developerModeActive = false; } + } + + if (_developerModeActive) { + this.gameObject.transform.GetChild (0).gameObject.SetActive (true); + } else { + this.gameObject.transform.GetChild (0).gameObject.SetActive (false); + } + } + + void btnToggleCheatsHandler() { + /* Handler for btnToggleCheats */ + if (CheatsAllowed) { + _cheatMenuOpen = !_cheatMenuOpen; + _pnlCheats.SetActive (_cheatMenuOpen); + } + } + + #region GetDebugLog + void OnEnable() { + Application.logMessageReceived += HandleLog; + } + void OnDisable() { + Application.logMessageReceived -= HandleLog; + } + public void HandleLog(string logString, string stackTrace, LogType type) { + string backLog = _lblConsoleLog.text; + _lblConsoleLog.text = logString + "\n" + backLog; + } + #endregion + +} diff --git a/td/Assets/Scripts/developerMode.cs.meta b/td/Assets/Scripts/developerMode.cs.meta new file mode 100644 index 0000000..7b3be6c --- /dev/null +++ b/td/Assets/Scripts/developerMode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 71d5bbff4cf5e434da6945e5ea1006af +timeCreated: 1506884902 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/enableChild.cs b/td/Assets/Scripts/enableChild.cs new file mode 100644 index 0000000..cba9375 --- /dev/null +++ b/td/Assets/Scripts/enableChild.cs @@ -0,0 +1,12 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class EnableChild : MonoBehaviour { + /* Denne klassen gjør ikke annet enn å aktivere det første childobjektet, + * nyttig om man vil skjule objekter når man designer, + * slik at man slipper å drive å skru objektene av og på mellom hver test manuelt */ + void Start () { + this.gameObject.transform.GetChild (0).gameObject.SetActive (true); + } +}
\ No newline at end of file diff --git a/td/Assets/Scripts/enableChild.cs.meta b/td/Assets/Scripts/enableChild.cs.meta new file mode 100644 index 0000000..ab87395 --- /dev/null +++ b/td/Assets/Scripts/enableChild.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c726586371a844ca1adc60878d0dadf1 +timeCreated: 1506778993 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/gameStats.cs b/td/Assets/Scripts/gameStats.cs new file mode 100644 index 0000000..731c276 --- /dev/null +++ b/td/Assets/Scripts/gameStats.cs @@ -0,0 +1,60 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine.UI; +using UnityEngine; + +public class GameStats : MonoBehaviour { + + public Player Player; + private GameObject _canvas; + private Text _txtMoney; + private Text _txtScore; + private Text _txtHp; + private Slider _sldHp; + private int _displayedScore; + private int _displayedMoney; + private int _displayedHealth; + + private void Start() { + _canvas = transform.GetChild (0).gameObject; + _txtMoney = _canvas.transform.Find ("playerMoney").gameObject.GetComponent <Text>(); + _txtScore = _canvas.transform.Find ("playerScore").gameObject.GetComponent <Text>(); + _sldHp = _canvas.transform.Find("playerHealth").gameObject.GetComponent<Slider>(); + } + + private void Update () { + + if (Player.Money () != _displayedMoney) { + _displayedMoney = Player.Money (); + UpdateMoney (_displayedMoney); + } + + if (Player.Score () != _displayedScore) { + _displayedScore = Player.Score (); + UpdateScore (_displayedScore); + } + + if (Mathf.RoundToInt(Player.HealthAsPercentage()) != Mathf.RoundToInt(_displayedHealth)) { + _displayedHealth = Player.HealthAsPercentage(); + UpdateHealth (_displayedHealth); + + if (_displayedHealth <= 10) { + _txtScore.color = Color.red; + } + } + + } + + private void UpdateScore(int newScore) { + _txtScore.text = ("Score: " + newScore.ToString ()); + } + + private void UpdateMoney(int newMoney) { + _txtMoney.text = ("Money: " + newMoney.ToString () + "$"); + } + + private void UpdateHealth(int newHp) { + _sldHp.value = newHp; + } + +} diff --git a/td/Assets/Scripts/gameStats.cs.meta b/td/Assets/Scripts/gameStats.cs.meta new file mode 100644 index 0000000..cd4989c --- /dev/null +++ b/td/Assets/Scripts/gameStats.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 48789fb36d2d543209c2f6540f1442d9 +timeCreated: 1507127936 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/mainGUI.cs b/td/Assets/Scripts/mainGUI.cs new file mode 100644 index 0000000..26ec78b --- /dev/null +++ b/td/Assets/Scripts/mainGUI.cs @@ -0,0 +1,187 @@ +using System; +using UnityEngine.UI; +using UnityEngine.SceneManagement; +using UnityEngine; + +public class MainGui : MonoBehaviour { + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set in designer + + private GameObject _pnlMenu; + private GameObject _pnlSidebar; + private GameObject _pnlSettings; + private GameObject _pnlGameOver; + private RectTransform _pnlSidebarTransform; + private Button _btnToggleSidebar; + private Button _btnPauseGame; + private Button _btnResumeGame; + private Button _btnExitGame; + private Button _btnSettings; + private Button _btnSettingsDiscard; + private Button _btnSettingsSave; + private Button _btnGoRetry; + private Button _btnGoMenu; + private Text _txtGoScore; + private Text _txtGoHighScore; + private Text _txtGoNewHighScore; + + private bool _sidebarExpanded; + private readonly float[] _sidebarStates = new float[2] {0f, -202.4f}; // The x position of the sidebar expanded or collapsed + + private bool _menuActive; + + private void Awake() { + /* Panels */ + _pnlMenu = transform.Find ("menu").gameObject; + _pnlSidebar = transform.Find ("sidebarWrapper").gameObject; + _pnlSettings = transform.Find ("settings").gameObject; + _pnlGameOver = transform.Find("GameOver").gameObject; + _pnlSidebarTransform = _pnlSidebar.GetComponent <RectTransform> (); + + /* Buttons */ + _btnToggleSidebar = _pnlSidebar.transform.Find("toggleSidebar").gameObject.GetComponent <Button> (); + _btnPauseGame = _pnlSidebar.transform.Find ("pauseGame").gameObject.GetComponent <Button> (); + _btnResumeGame = _pnlMenu.transform.Find ("resumeGame").gameObject.GetComponent <Button> (); + _btnExitGame = _pnlMenu.transform.Find ("exitGame").gameObject.GetComponent <Button> (); + _btnSettings = _pnlMenu.transform.Find ("settings").gameObject.GetComponent <Button> (); + _btnSettingsDiscard = _pnlSettings.transform.Find ("discardChanges").gameObject.GetComponent <Button> (); + _btnSettingsSave = _pnlSettings.transform.Find ("saveChanges").gameObject.GetComponent <Button> (); + _btnGoMenu = _pnlGameOver.transform.Find ("GameOver").transform.Find("menu").gameObject.GetComponent <Button> (); + _btnGoRetry = _pnlGameOver.transform.Find ("GameOver").transform.Find("restart").gameObject.GetComponent <Button> (); + if (_btnToggleSidebar != null) { _btnToggleSidebar.onClick.AddListener (toggleSidebarHandler); } + if (_btnPauseGame != null) { _btnPauseGame.onClick.AddListener (pauseGameHandler); } + if (_btnResumeGame != null) { _btnResumeGame.onClick.AddListener (btnResumeGameHandler); } + if (_btnExitGame != null) { _btnExitGame.onClick.AddListener (btnExitGameHandler); } + if (_btnSettings != null) { _btnSettings.onClick.AddListener (btnSettingsHandler); } + if (_btnSettingsDiscard != null) { _btnSettingsDiscard.onClick.AddListener (btnSettingsDiscardHandler); } + if (_btnSettingsSave != null) { _btnSettingsSave.onClick.AddListener (btnSettingsSaveHandler); } + if (_btnGoMenu != null) { _btnGoMenu.onClick.AddListener (btnGoMenuHandler); } + if (_btnGoRetry != null) { _btnGoRetry.onClick.AddListener (btnGoRetryHandler); } + + /* Text */ + _txtGoScore = _pnlGameOver.transform.Find ("GameOver").transform.Find("score").gameObject.GetComponent<Text>(); + _txtGoHighScore = _pnlGameOver.transform.Find ("GameOver").transform.Find("highScore").gameObject.GetComponent<Text>(); + _txtGoNewHighScore = _pnlGameOver.transform.Find ("GameOver").transform.Find("newHighscore").gameObject.GetComponent<Text>(); + + /* Set up initial states */ + UpdateSidebarPosandBtn (); + _pnlMenu.SetActive (false); + _pnlSettings.SetActive (false); + _pnlGameOver.SetActive(false); + } + + private void toggleSidebarHandler() { + /* handler for btnToggleSidebar */ + _sidebarExpanded = !_sidebarExpanded; + UpdateSidebarPosandBtn (); + } + + private void pauseGameHandler() { + /* handler for btnPauseGame */ + _menuActive = true; + _pnlMenu.SetActive (_menuActive); + Time.timeScale = 0.0F; + _btnToggleSidebar.interactable = false; + _btnPauseGame.interactable = false; + Player.PauseGame(); + } + + private void btnResumeGameHandler() { + /* handler for btnResumeGame */ + _menuActive = false; + _pnlMenu.SetActive (_menuActive); + Time.timeScale = 1.0F; + _btnToggleSidebar.interactable = true; + _btnPauseGame.interactable = true; + Player.ResumeGame(); + } + + private void btnExitGameHandler() { + /* handler for btnExitGame */ + Application.Quit (); + } + + private void btnSettingsHandler() { + /* handler for btnSettings */ + _pnlMenu.SetActive (false); + _pnlSettings.SetActive (true); + + if (PlayerPrefs.HasKey ("developerMode")) { + _pnlSettings.transform.Find ("developerEnabled").gameObject.GetComponent <Toggle> ().isOn = IntToBool(PlayerPrefs.GetInt ("developerMode")); + } + } + + private void btnSettingsSaveHandler() { + /* handler for btnSaveSettings */ + _pnlMenu.SetActive (true); + _pnlSettings.SetActive (false); + + PlayerPrefs.SetInt ("developerMode", Convert.ToInt32(_pnlSettings.transform.Find ("developerEnabled").gameObject.GetComponent <Toggle>().isOn)); + } + + private void btnSettingsDiscardHandler() { + /* handler for btnSettingsDiscard */ + _pnlMenu.SetActive (true); + _pnlSettings.SetActive (false); + } + + private void UpdateSidebarPosandBtn() { + /* update state of sidebar based on the expanded var */ + if (_sidebarExpanded) { + _pnlSidebarTransform.localPosition = new Vector3 (_sidebarStates [1], 0f, 0f); + _btnToggleSidebar.transform.GetComponent <RectTransform> ().localScale = new Vector3 (-1, 1, 1); + } else { + _pnlSidebarTransform.localPosition = new Vector3 (_sidebarStates [0], 0f, 0f); + _btnToggleSidebar.transform.GetComponent <RectTransform> ().localScale = new Vector3 (1, 1, 1); + } + } + + private void btnGoMenuHandler() { + /* Handler for btnGoMenu */ + } + + private void btnGoRetryHandler() { + /* Handler for btnGoRetry */ + SceneManager.LoadScene(SceneManager.GetActiveScene().name); + Time.timeScale = 1.0F; + } + + private bool IntToBool(int input) { + /* Converts int to boolean */ + if (input >= 1) { + return true; + } else { + return false; + } + } + + public void GameOverScreen(int score) { + /* Show game over screen */ + bool newHighscore = false; + int highScore = 0; + + if (PlayerPrefs.HasKey("highscore")) { + highScore = PlayerPrefs.GetInt("highscore"); + if (score > highScore) { + newHighscore = true; + } + } + + if (_sidebarExpanded) { toggleSidebarHandler(); } + + /* Pause game */ + Player.PauseGame(); + /* Activate panel */ + _pnlGameOver.SetActive(true); + /* Set text, score */ + _txtGoScore.text = "Score: " + score.ToString(); + /* set text, highscore */ + _txtGoHighScore.text = "Highscore: " + highScore.ToString(); + /* set newHicgscore */ + _txtGoNewHighScore.gameObject.SetActive(newHighscore); + /* Disable other onScreenButtons */ + _btnToggleSidebar.interactable = false; + _btnPauseGame.interactable = false; + } + +} diff --git a/td/Assets/Scripts/mainGUI.cs.meta b/td/Assets/Scripts/mainGUI.cs.meta new file mode 100644 index 0000000..bbfc14a --- /dev/null +++ b/td/Assets/Scripts/mainGUI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6953b687c28724842b2c9d48f701cf75 +timeCreated: 1506770005 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/player.cs b/td/Assets/Scripts/player.cs new file mode 100644 index 0000000..cb55357 --- /dev/null +++ b/td/Assets/Scripts/player.cs @@ -0,0 +1,85 @@ +using UnityEngine; + +public class Player : MonoBehaviour { + + public int InitialHealth; + public int StartingMoney; + public MainGui MainGui; + + private int _gameState; + private GameObject[] _towers; + private int _playerMoney; + private int _playerScore; + private int _playerHealth; + + void Awake() { + /* This method initializes the player class */ + _playerMoney = StartingMoney; + _playerHealth = InitialHealth; + InvokeRepeating ("GameStateWatcher", 0f, 0.5f); + _gameState = 1; + } + + #region stats + public int Score() { + return _playerScore; + } + + public void ScoreAdd(int points) { + _playerScore += points; + } + + public int Money() { + return _playerMoney; + } + + public void MoneyAdd(int sum) { + _playerMoney += sum; + } + + public void MoneySubtract(int sum) { + _playerMoney -= sum; + } + + public int Health() { + return _playerHealth; + } + + public int HealthAsPercentage() + { + return Mathf.RoundToInt((InitialHealth * _playerHealth) / 100.0f); // Basic percentage calc... + } + + public void DecreaseHealth(int hp) { + _playerHealth -= hp; + } + #endregion + + public void SpawnTower(GameObject towerType) { + GameObject tower = Instantiate (towerType, new Vector3 (0, 0, 0), Quaternion.identity, transform.Find ("towers").transform); + Tower script = tower.GetComponent <Tower>(); + script.Player = this; + } + + public void GameStateWatcher() { + if (_playerHealth <= 0) { + MainGui.GameOverScreen(_playerScore); + } + } + + public bool GameIsPaused() { + if (_gameState == 0) { return true; } + return false; + } + + public void PauseGame() { + Time.timeScale = 0.0F; + _gameState = 0; + } + + public void ResumeGame() { + Time.timeScale = 1.0F; + _gameState = 1; + } + +} diff --git a/td/Assets/Scripts/player.cs.meta b/td/Assets/Scripts/player.cs.meta new file mode 100644 index 0000000..c57a461 --- /dev/null +++ b/td/Assets/Scripts/player.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b033e147f0b23409bb5c7a98a7208d6b +timeCreated: 1507125120 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/tower.cs b/td/Assets/Scripts/tower.cs new file mode 100644 index 0000000..004605b --- /dev/null +++ b/td/Assets/Scripts/tower.cs @@ -0,0 +1,145 @@ +using UnityEngine; + +public class Tower : MonoBehaviour { + + [Header("Attributes")] + public int TowerPrice; // The price of the tower, set this in the desiger (tower prefab) + public float FireRate; // How long the turret should use to reload, Set in designer (tower prefab) + public float TurnSpeed; // How fast the turret should rotate. Set in designer (tower prefab) + [Range(0, 10)] + public float TowerRange; // How large the range of the tower is. this is the diameter. Set in designer (tower prefab) + public GameObject ProjectilePrefab; + public Transform FirePoint; + [Header("Materials")] + public Material MaterialDanger; // The material used when tower can't be placed, set in the designer (tower prefab) + public Material MaterialSuccess; // The material used when the tower can be placed, or is selected, set in the designer (tower prefab) + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set when instantiating + + private GameObject _placementIndicator; // The placement indicator + private Renderer _placementIndicatorRenderer; // The renderer of the placement indicator + private Plane _groundPlane; // Plane used for raycasting when placing tower + private float _groundYpoint = 0.525f; // What Y-position the Tower should be placed on, this should be constant in every use-case. + private bool _towerPlaced; // Bool used to descide what to do this frame + private bool _colliding; // Set if the tower collides with any GameObject, used when placing, to see where it can be placed + + private Transform _target; + private float _fireCountdown; + + void Start () { + _placementIndicator = transform.GetChild (0).gameObject; + _placementIndicatorRenderer = _placementIndicator.GetComponent<Renderer> (); + _placementIndicator.transform.localScale = new Vector3 (TowerRange*7, 0.00000001f, TowerRange*7); + + _groundPlane = new Plane (Vector3.up, new Vector3(0f, _groundYpoint, 0f)); + } + + void Update () { + + #region placeTower + if (!_towerPlaced) { + if (Input.touchCount == 1 || Input.GetMouseButton (0)) { + + /* Activate indicator if not already */ + if (!_placementIndicator.activeSelf) { _placementIndicator.SetActive (true); } + /* Change indicator-color based on placement */ + if (!_colliding) { _placementIndicatorRenderer.sharedMaterial = MaterialDanger; } + else { _placementIndicatorRenderer.sharedMaterial = MaterialSuccess; } + /* Calculate new position */ + Ray touchRay = Camera.main.ScreenPointToRay (Input.mousePosition); + float rayDistance; + if (_groundPlane.Raycast (touchRay, out rayDistance)) { + transform.position = touchRay.GetPoint (rayDistance); + } + + } else { + + /* User let go of the screen, decide if tower can be placed */ + if (!_colliding) { Destroy (gameObject); } // Skal kollidere for å være på et godkjent område + else { + _towerPlaced = true; + Player.MoneySubtract (TowerPrice); + _placementIndicator.SetActive (false); + _placementIndicatorRenderer.sharedMaterial = MaterialSuccess; + InvokeRepeating ("UpdateTarget", 0f, 0.5f); // This starts the + gameObject.GetComponent <BoxCollider>().enabled = false; + } + + } + + return; + } + #endregion + + // Stop rest of update if no target is aquired + if (_target == null) { + return; + } + // Target lockon + Vector3 direction = _target.position - transform.position; + Quaternion lookRotation = Quaternion.LookRotation (direction); + Vector3 rotation = Quaternion.Lerp (transform.rotation, lookRotation, Time.deltaTime * TurnSpeed).eulerAngles; + transform.rotation = Quaternion.Euler (0f, rotation.y, 0f); + + if (_fireCountdown <= 0f) { + // FAIAAAAA + Shoot(); + _fireCountdown = 1f / FireRate; + } + + _fireCountdown -= Time.deltaTime; + + } + + void Shoot() { + GameObject projectileGo = (GameObject) Instantiate (ProjectilePrefab, FirePoint.position, FirePoint.rotation); + Projectile projectile = projectileGo.GetComponent <Projectile>(); + if (projectile != null) { + projectile.Player = Player; + projectile.Seek (_target); + } + } + + void UpdateTarget() { + /* Method that updates the currentTarget. + * The target will be set to the nearest in range */ + GameObject[] enemies = GameObject.FindGameObjectsWithTag ("enemy"); + float shortestDistance = Mathf.Infinity; + GameObject nearestEnemy = null; + + foreach (var enemy in enemies) { + float distanceToEnemy = Vector3.Distance (transform.position, enemy.transform.position); + if (distanceToEnemy < shortestDistance) { + shortestDistance = distanceToEnemy; + nearestEnemy = enemy; + } + } + + if (nearestEnemy != null && shortestDistance <= TowerRange) { + _target = nearestEnemy.transform; + } else { + _target = null; + } + } + + void OnTriggerEnter(Collider other) { + _colliding = true; + } + + void OnTriggerStay(Collider other) { + _colliding = true; + } + + void OnTriggerExit(Collider other) { + _colliding = false; + } + + void OnDrawGizmosSelected() { + /* Show gizmos in designer */ + Gizmos.color = Color.red; + Gizmos.DrawWireSphere (transform.position, TowerRange); + } + +} + + diff --git a/td/Assets/Scripts/tower.cs.meta b/td/Assets/Scripts/tower.cs.meta new file mode 100644 index 0000000..c31ac8e --- /dev/null +++ b/td/Assets/Scripts/tower.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 39d4d93c762d74a628b6292b97f1483f +timeCreated: 1506962845 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/td/Assets/Scripts/waveSpawner.cs b/td/Assets/Scripts/waveSpawner.cs new file mode 100644 index 0000000..3a6d7d4 --- /dev/null +++ b/td/Assets/Scripts/waveSpawner.cs @@ -0,0 +1,125 @@ +using System.Collections; +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +public class WaveSpawner : MonoBehaviour { + + [Header("Attributes")] + public float TimeBetweenWaves; + public float SpawnRate; + + [Header("Objects")] + public Transform SpawnPoint; + public Transform PathWay; + public Text WaveCountdownText; + + [Header("Every possible enemy")] + public EnemyType[] Enemies; + + [Header("Scripting vars")] + public Player Player; // Reference to the player object, should be set in designer + + private Transform _parentObject; + private List<Vector3> _waypoints = new List<Vector3>(); + + public static int EnemiesAlive = 0; + private float _countdown = 2f; + private int _waveIndex = 0; + + void Awake() { + foreach (Transform child in PathWay) { + _waypoints.Add (child.position); + } + } + + void Start() { + _parentObject = transform.Find ("enemies").gameObject.GetComponent <Transform> (); + } + + void Update () { + if (EnemiesAlive > 0) { + return; + } + + if (_countdown <= 0f) { + StartCoroutine(SpawnWave()); + _countdown = TimeBetweenWaves; + return; + } + + _countdown -= Time.deltaTime; + _countdown = Mathf.Clamp(_countdown, 0f, Mathf.Infinity); + //waveCountdownText.text = string.Format("{0:00.00}", countdown); + } + + private int WaveEnemyCount(int waveNum) { + // 10.64 * e^0,57x + float pow = (float) Math.Pow( Math.E, 0.57f * waveNum); + return (int) Math.Floor(10.64f * pow); + } + + private float EnemyAmountThing(int currentEnemy, int maxTypes) { + // TODO Change the for loop into a faster method + float rest = 1; + + for (int i=1; i <= maxTypes; i++) { + if (i != maxTypes) { rest = rest / 2; } + if (i == currentEnemy + 1) { return rest; } + } + + return 0; + } + + IEnumerator SpawnWave () { + int enemiesToSpawn = WaveEnemyCount(_waveIndex); + EnemiesAlive = enemiesToSpawn; + List<WaveElement> wave = new List<WaveElement>(); + + for (int i = 0; i < Enemies.Length; i++) { + EnemyType enemy = Enemies[i]; + + float amount = enemiesToSpawn * EnemyAmountThing(i, Enemies.Length); + if (amount >= 1) { + wave.Add(new WaveElement {Prefab = enemy.Enemy, Amount = (int)Math.Floor(amount)} ); + } + + } + + foreach (var enemyType in wave) { + for (int i = 0; i < enemyType.Amount; i++) { + SpawnEnemy(enemyType.Prefab); + yield return new WaitForSeconds(1f / SpawnRate); + } + yield return new WaitForSeconds(1f / 100f); + } + + SpawnRate = SpawnRate * 2; + _waveIndex++; + } + + void SpawnEnemy (GameObject enemyPrefab) { + GameObject newEnemy = Instantiate (enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity, _parentObject); + Enemy script = newEnemy.GetComponent <Enemy> (); + Transform transform = newEnemy.GetComponent <Transform>(); + + script.Waypoints = _waypoints; + script.Player = Player; + transform.position = new Vector3 (0.93f, 0.483f, 0f); + } + + [System.Serializable] + public class EnemyType { + public string Name; + public GameObject Enemy; + [Range(0, 1)] + public float Percentage; + } + + public class WaveElement { + public GameObject Prefab { get; set; } + public int Amount { get; set; } + } + +}
\ No newline at end of file diff --git a/td/Assets/Scripts/waveSpawner.cs.meta b/td/Assets/Scripts/waveSpawner.cs.meta new file mode 100644 index 0000000..1f1e3cb --- /dev/null +++ b/td/Assets/Scripts/waveSpawner.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9ea53d824cbfc4eb8a4eb4ee6a247bc7 +timeCreated: 1507241433 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: |