Newer
Older
Dreamsturbia-Project-IADE-Unity3D / Assets / Scripts / Player / PlayerSight.cs
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PlayerSight : MonoBehaviour
  5. {
  6. private Camera mainCamera;
  7. private ILookAround target;
  8. public static LinkedList<GameObject> gameObjects = new LinkedList<GameObject>();
  9. public static HashSet<GameObject> canSee = new HashSet<GameObject>(8);
  10. private Transform player;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. mainCamera = Camera.main;
  15. player = GameObject.FindGameObjectWithTag("Player")?.transform;
  16. }
  17. /* private void OnDrawGizmos()
  18. {
  19. if (player != null)
  20. {
  21. Gizmos.color = Color.green;
  22. foreach (GameObject g in gameObjects)
  23. {
  24. // Vector3 direction = g.transform.position - mainCamera.transform.position;
  25. Vector3 direction = GetSightDirection();
  26. Gizmos.DrawRay(transform.position, direction);
  27. }
  28. }
  29. }*/
  30. // Update is called once per frame
  31. void Update()
  32. {
  33. // canSee.Clear();
  34. if (player != null)
  35. {
  36. foreach (GameObject g in gameObjects)
  37. {
  38. Vector3 pos = mainCamera.WorldToViewportPoint(g.transform.position);
  39. if (pos.x > 0 && pos.x < 1 && pos.y > 0 && pos.y < 1)
  40. {
  41. // Ray r = mainCamera.ViewportPointToRay(pos);
  42. Vector3 direction = g.transform.position - mainCamera.transform.position;
  43. Ray r = new Ray(mainCamera.transform.position, GetSightDirection());
  44. TestRaycast(r);
  45. }
  46. }
  47. }
  48. }
  49. private Vector3 GetSightDirection()
  50. {
  51. Vector3 offset = player.transform.position + (player.transform.forward * 2);
  52. return Vector3.Normalize(offset- new Vector3(mainCamera.transform.position.x, offset.y, mainCamera.transform.position.z));
  53. }
  54. private void TestRaycast(Ray r)
  55. {
  56. RaycastHit hit;
  57. if (Physics.Raycast(r, out hit, mainCamera.farClipPlane, LayerMask.GetMask("Nightmare"), QueryTriggerInteraction.Collide))
  58. {
  59. ILookAround e = hit.collider.GetComponent<ILookAround>();
  60. Debug.Log(gameObject);
  61. if (e != null)
  62. {
  63. // canSee.Add(hit.collider.transform.parent.gameObject);
  64. if (target != e && gameObject.transform.parent != null)
  65. {
  66. e.Looking(gameObject.transform.parent.gameObject, true);
  67. if (target != null)
  68. {
  69. target.Looking(null, false);
  70. }
  71. target = e;
  72. }
  73. }
  74. else
  75. {
  76. // canSee.Remove(hit.collider.gameObject);
  77. if (target != null)
  78. {
  79. target.Looking(null, false);
  80. target = null;
  81. }
  82. }
  83. }
  84. }
  85. }