Example #1
0
    void Update()
    {
        // set the origin and direction of the ray to match the weapon/player's transformation
        _ray.origin    = transform.position;
        _ray.direction = transform.forward;

        // set the starting vertex of the beam to the weapon/player position
        _beam.SetPosition(0, _ray.origin);

        // by default, the end vertex of the ray is the max forward distance from its origin
        Vector3 endVertex = _ray.origin + (_ray.direction * maxRange);

        // cast a ray and collect data on all of the objects it hits
        RaycastHit[] hits;
        hits = Physics.RaycastAll(_ray, maxRange, layerMask);

        // sort the hits from nearest to farthest
        Array.Sort(hits, delegate(RaycastHit first, RaycastHit second)
        {
            return((int)(first.distance - second.distance));
        });

        if (hits.Length > 0)
        {
            RaycastHit hit = hits[0];

            // make sure the colliding object is one of the defined targets
            if (_damageSystem.IsTarget(hit.collider.gameObject.tag))
            {
                _damageSystem.DamageObject(hit.collider.gameObject);
            }

            endVertex = hit.point;
        }

        // set the end vertex of the beam according to raycast collisions and amount of piercings
        _beam.SetPosition(1, endVertex);
        impactParticles.position = endVertex;
        impactParticles.rotation = Quaternion.LookRotation(transform.position - endVertex);

        // update the remaining time for the beam
        _beamDuration  -= Time.deltaTime;
        _continueFiring = false;
    }