Exemplo n.º 1
0
 private void Start()
 {
     sightState   = GetComponent <SightState>();
     meshRenderer = GetComponent <MeshRenderer>();
     VisualizeState(false);
     sightState.SightStateChanged += OnSightStateChanged;
 }
Exemplo n.º 2
0
        private void Update()
        {
            rayDirections.Clear();
            float startingAngle = -sightAngle / 2;

            for (int i = 0; i <= sections; ++i)
            {
                rayDirections.Add(Quaternion.AngleAxis(startingAngle + i * rayAngle, transform.right) * transform.forward);
            }

            RaycastHit2D      hit;
            List <SightState> hitObjects = new List <SightState>();

            vertices = new List <Vector3>()
            {
                transform.localPosition
            };

            foreach (Vector3 direction in rayDirections)
            {
                float distance = sightRange;

                if (hit = Physics2D.Raycast(transform.position, direction, sightRange, 1 << 9))
                {
                    distance = hit.distance;
                }

                vertices.Add(transform.InverseTransformPoint(transform.position + (direction * distance)));

                //Debug.DrawRay(transform.position, direction * distance, Color.yellow, Time.deltaTime);

                foreach (RaycastHit2D raycastHit in Physics2D.RaycastAll(transform.position, direction, distance))
                {
                    SightState sightState = raycastHit.collider.gameObject.GetComponent <SightState>();
                    if (sightState != null)
                    {
                        sightState.SetSightState(true);
                        hitObjects.Add(sightState);
                    }
                }

                IEnumerable <SightState> lostSight = objectsInSight.Where(sightState => hitObjects.Contains(sightState) == false);
                foreach (SightState sightState in lostSight)
                {
                    sightState.SetSightState(false);
                }

                objectsInSight = hitObjects;
            }

            UpdateMesh();
        }