示例#1
0
    void Awake()
    {
        fl    = transform.Find("Wheels/PivotFL");
        fr    = transform.Find("Wheels/PivotFR");
        rl    = transform.Find("Wheels/PivotRL");
        rr    = transform.Find("Wheels/PivotRR");
        motor = GetComponent <TrafPCH>();

        var rend = GetComponentInChildren <Renderer>();

        visPasser = rend.gameObject.AddComponent <OnBecameVisiblePass>();
        visPasser.onVisbilityChange = OnVisibilityChange;
    }
    void EnvironmentDetect()
    {
        float currentSpeed = gameObject.GetComponent <VehicleController>().CurrentSpeed;
        int   safetyDist   = Mathf.RoundToInt(Mathf.Pow(currentSpeed / 10, 2));

        if (safetyDist < 50)
        {
            safetyDist = 50;
        }
        LayerMask mask = (/*1 << LayerMask.NameToLayer("Traffic")) | (1 << LayerMask.NameToLayer("obstacle")) |*/ 1 << LayerMask.NameToLayer("EnvironmentProp") | 1 << LayerMask.NameToLayer("Signage") | 1 << LayerMask.NameToLayer("Roads")); //restrict OverlapSphere only to the layers of interest

        Collider[]          colls    = Physics.OverlapSphere(gameObject.transform.position, safetyDist, mask);
        HashSet <Transform> curColls = new HashSet <Transform>(); //this is to store the root transform of the colliders returned by OverlapSphere

        Timer -= Time.deltaTime;                                  //thanks to this timer cubes and tags are instantiated only every 0.1 ms
        if (Timer <= 0f)
        {
            foreach (KeyValuePair <GameObject, GameObject> pair in cubesAndTags)
            {
                Destroy(pair.Key);
                Destroy(pair.Value);
                //Debug.Log("destroyed" + g + "update is: " + i);
            }
            cubesAndTags.Clear();

            foreach (Collider c in colls)
            {
                switch (c.gameObject.layer)
                {
                case 16:      //EnvironmentProp
                {
                    Bounds bounds = new Bounds();
                    if (c.transform.name.StartsWith("BasicCar"))
                    {
                        BoxCollider boxCol = c as BoxCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * boxCol.center;
                        bounds.size   = boxCol.size;
                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;         //infoTag trasl
                        traslL = new Vector3(traslL.x * 0.5f + 2.0f, traslL.y * 0.5f, 0);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);

                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 50.0f)
                        {
                            infos[0] = "0" + " KPH";         //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], transform.rotation, infos, Color.white));
                        }
                    }
                    else if (c.transform.tag.Equals("Sign"))
                    {
                        BoxCollider boxCol = c as BoxCollider;
                        bounds.center = boxCol.center;
                        bounds.size   = boxCol.size * 1.25f;
                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 50.0f)
                        {
                            infos[0] = "0" + " KPH";         //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), new GameObject());         //at the moment i don't need an InfoTag
                        }
                    }
                    switch (c.transform.name)
                    {
                    case "streetlight":
                    {
                        CapsuleCollider capsCol = c as CapsuleCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * capsCol.center;
                        bounds.size   = new Vector3(capsCol.radius * 4.0f, capsCol.radius * 4.0f, capsCol.height);
                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;                 //infoTag trasl
                        traslL = new Vector3(traslL.x * 0.5f + 2.0f, 0, 0);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);

                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 10.0f)
                        {
                            infos[0] = "0" + " KPH";                 //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                            infos[2] = "";
                            RaycastHit hit;
                            Vector3    fwd   = rayCastPos.TransformDirection(Vector3.forward);
                            bool       isHit = Physics.Raycast(rayCastPos.position, fwd, out hit, 10.0f);
                            if (isHit)
                            {
                                //Debug.DrawLine(rayCastPos.position, hit.point, Color.yellow);
                                GameObject boundingCube = CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size);
                                GameObject infotag      = CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[29], transform.rotation, infos, Color.red);
                                StartCoroutine(HideUnhide(infotag, isHit));
                                cubesAndTags.Add(boundingCube, infotag);
                            }
                            else
                            {
                                //Debug.DrawLine(rayCastPos.position, rayCastPos.position + (fwd * 10.0f), Color.magenta);
                                cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], transform.rotation, infos, Color.white));
                            }
                        }
                    }
                    break;

                    case "tree_dec01":
                    {
                        Transform oldParent = c.transform.parent;
                        c.transform.parent = null;                 //I am forced to unparent since I can't take into account the parent scale in the bounding box computation
                        CapsuleCollider capsCol = c as CapsuleCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * new Vector3(capsCol.center.x * c.transform.localScale.x, capsCol.center.y * c.transform.localScale.y, capsCol.center.z * c.transform.localScale.z);
                        bounds.size   = new Vector3(capsCol.radius * 2.0f * c.transform.localScale.x, capsCol.radius * 2.0f * c.transform.localScale.y, capsCol.height * c.transform.localScale.z);
                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;                 //infoTag trasl
                        traslL = new Vector3(traslL.x * 0.5f + 3.0f, 0, 0);
                        Debug.Log(c.transform.name + ", " + traslL);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);

                        c.transform.parent = oldParent;

                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 10.0f)
                        {
                            infos[0] = "0" + " KPH";                 //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], transform.rotation, infos, Color.white));
                        }
                    }
                    break;

                    case "Dumpster":

                    case "busstop":

                    case "barrier_concrete":

                    case "barrier_metal":

                    case "Lamppost":

                    case "Table_For2":

                    case "Table_For4":
                    {
                        BoxCollider boxCol = c as BoxCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * new Vector3(boxCol.center.x * c.transform.localScale.x, boxCol.center.y * c.transform.localScale.y, boxCol.center.z * c.transform.localScale.z);
                        bounds.size   = new Vector3(boxCol.size.x * c.transform.localScale.x, boxCol.size.y * c.transform.localScale.y, boxCol.size.z * c.transform.localScale.z);
                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;                 //infoTag trasl
                        traslL = new Vector3(traslL.x * 0.5f + 2.0f, traslL.y * 0.5f, 0);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);

                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 10.0f)
                        {
                            infos[0] = "0" + " KPH";                 //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], transform.rotation, infos, Color.white));
                        }
                    }
                    break;
                    }
                }
                break;

                case 17:      //Signage
                {
                    Bounds bounds = new Bounds();
                    if (c.transform.parent.name.Equals("StreetArrows") || c.transform.name.Equals("Post"))
                    {
                        break;
                    }

                    BoxCollider boxCol = c as BoxCollider;
                    bounds.center = boxCol.center;
                    bounds.size   = boxCol.size * 1.25f;
                    float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                    if (dist <= 50.0f)
                    {
                        infos[0] = "0" + " KPH";         //speed of EnvironmentProp is null
                        infos[1] = Mathf.RoundToInt(dist).ToString() + " M";
                        infos[2] = "";
                        cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), new GameObject());
                    }
                }
                break;

                case 12:     //obstacle
                {
                    Bounds bounds = ComputeBounds(c.transform);
                    infos[0] = Mathf.RoundToInt(CalculateObstacleSpeed(c.transform)).ToString() + " KPH";
                    infos[1] = Mathf.RoundToInt(CalculateDistance(rayCastPos.position, bounds.center)).ToString() + " M";
                    infos[2] = "";
                    //cubesAndTags.Add(CreateBoundingCube(c.transform, bounds.center, bounds.size), CreateInfoTag(bounds.center, bounds.size, sprites[28], infos));
                }
                break;

                case 8:
                {         //Traffic
                    if (!curColls.Contains(c.transform.root))
                    {     //this is in order to check if an object has more colliders than one; if so, one is sufficient so simply discard other otherwise the cube instantiated would be equal to the number of colliders
                        Bounds  bounds  = ComputeBounds(c.transform.root);
                        TrafPCH trafPCH = c.transform.root.GetComponent <TrafPCH>();
                        if (trafPCH != null)
                        {
                            float speed = trafPCH.currentSpeed;
                            infos[0] = Mathf.RoundToInt(speed * 3.6f).ToString() + " KPH";
                            infos[1] = Mathf.RoundToInt(CalculateDistance(rayCastPos.position, bounds.center)).ToString() + " M";
                            infos[2] = "";
                            //cubesAndTags.Add(CreateBoundingCube(c.transform.root, bounds.center, bounds.size), CreateInfoTag(bounds.center, bounds.size, sprites[0], infos));
                            curColls.Add(c.transform.root);
                        }
                    }
                }
                break;

                case 18:     //Roads
                {
                    if (c.transform.name.StartsWith("TrafficLight"))
                    {
                        TrafLightState currentState = c.transform.GetComponent <TrafficLightContainer>().State;
                        Dictionary <string, Transform> trafLightChildren = new Dictionary <string, Transform>();
                        List <Bounds> bounds = new List <Bounds>();
                        foreach (Transform t in c.transform)
                        {
                            if (t.name.StartsWith("Light") && t.gameObject.activeInHierarchy)         //there are some trafficLights not active so I have to exclude them
                            {
                                trafLightChildren.Add(t.name, t);
                                bounds.Add(ComputeBounds(t));
                            }
                        }
                        if (trafLightChildren.Count != 0)           //I have to check whether the dictionary is empty or not since there may be some inactive trafficLights which in the next code I will erronously reference
                        {
                            infos[0] = infos[1] = "";
                            if (currentState.Equals(TrafLightState.GREEN))
                            {
                                infos[2] = "GO";
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light0"], bounds[0].center, bounds[0].size), CreateInfoTag(bounds[0].center, new Vector3(0, 0, -bounds[0].size.x), new Vector3(0, 0, -bounds[0].size.x), sprites[25], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light0"].rotation, infos, Color.white));       //I add another 90 degrees to position the tag orthogonally with respect to the trafficLight
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light1"], bounds[1].center, bounds[1].size), CreateInfoTag(bounds[1].center, new Vector3(0, 0, -bounds[1].size.x), new Vector3(0, 0, -bounds[1].size.x), sprites[25], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light1"].rotation, infos, Color.white));
                            }
                            else if (currentState.Equals(TrafLightState.YELLOW))
                            {
                                infos[2] = "GO";
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light0"], bounds[0].center, bounds[0].size), CreateInfoTag(bounds[0].center, new Vector3(0, 0, -bounds[0].size.x), new Vector3(0, 0, -bounds[0].size.x), sprites[27], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light0"].rotation, infos, Color.white));
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light1"], bounds[1].center, bounds[1].size), CreateInfoTag(bounds[1].center, new Vector3(0, 0, -bounds[1].size.x), new Vector3(0, 0, -bounds[1].size.x), sprites[27], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light1"].rotation, infos, Color.white));
                            }
                            else
                            {
                                infos[2] = "STOP";
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light0"], bounds[0].center, bounds[0].size), CreateInfoTag(bounds[0].center, new Vector3(0, 0, -bounds[0].size.x), new Vector3(0, 0, -bounds[0].size.x), sprites[26], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light0"].rotation, infos, Color.white));
                                cubesAndTags.Add(CreateBoundingCube(trafLightChildren["Light1"], bounds[1].center, bounds[1].size), CreateInfoTag(bounds[1].center, new Vector3(0, 0, -bounds[1].size.x), new Vector3(0, 0, -bounds[1].size.x), sprites[26], Quaternion.Euler(0f, 90f, 0f) * trafLightChildren["Light1"].rotation, infos, Color.white));
                            }
                        }
                    }
                }
                break;
                }
            }
            Timer = 0.1f;
        }
        //i++;
    }
    void FixedUpdate()
    {
        var predicted = GetPredictedPoint();
        var normal    = GetNormalPoint(predicted, currentWaypoint, nextWaypoint);

        if (evitare && hitInfo.collider != null && hitInfo.collider.gameObject.layer == 12)
        {
            evita();
            return;
        }
        if (inchiodare && hitInfo.collider != null && hitInfo.collider.gameObject.layer == 12)
        {
            inchioda();
            return;
        }

        if (sosta)
        {
            sostaDopoPericolo();
            return;
        }

        //check if we are heading past the current waypoint
        if (Vector3.Dot(normal - nextWaypoint, nextWaypoint - currentWaypoint) >= 0)
        {
            contatore++;
            currentWaypoint      = nextWaypoint;
            currentNode          = nextNode;
            currentWaypointIndex = nextWaypointIndex;
            UpdateNextWaypoint();
        }


        if (Vector3.Distance(transform.position, new Vector3(target.x, transform.position.y, target.z)) <= 10f || target == Vector3.zero)
        {
            RoadPathNode prossimoNodo5 = path.pathNodes[currentWaypointIndex + 2];
            target = prossimoNodo5.position;
        }


        //lancio il raggio per vedere cosa ho davanti
        if (Time.time > nextRaycast)
        {
            hitInfo          = new RaycastHit();
            somethingInFront = CheckFrontBlocked(out hitInfo);
            nextRaycast      = NextRaycastTime();
        }
        if (somethingInFront)
        {
            if (hitInfo.collider.gameObject.name.Equals("RocciaTest"))
            {
                vehicleController.accellInput = -0.18f;
                if (hitInfo.distance < 15f)
                {
                    vehicleController.steerInput = -8f / 45f;
                }
                return;
            }
            if (hitInfo.rigidbody != null && ((hitInfo.rigidbody.tag.Equals("TrafficCar")) || hitInfo.rigidbody.tag.Equals("DangerousCar") || hitInfo.rigidbody.gameObject.layer.Equals(12)))
            {
                if (hitInfo.rigidbody.tag.Equals("TrafficCar") || hitInfo.rigidbody.tag.Equals("DangerousCar"))
                {
                    Debug.DrawLine(this.transform.position, hitInfo.transform.position);
                    if (hitInfo.distance <= 35f)
                    {
                        TrafPCH macchinaDavanti = hitInfo.rigidbody.GetComponent <TrafPCH>();
                        float   frontSpeed      = macchinaDavanti.currentSpeed;

                        float  velocitaTarget          = Mathf.Min(targetSpeed, (frontSpeed - 0.25f));
                        float  miaVelocita             = this.GetComponent <Rigidbody>().velocity.magnitude;
                        double distanzaSicurezzaUpdate = (Math.Pow((this.GetComponent <Rigidbody>().velocity.magnitude * 3.6f / 10f), 2) + 5f); //+ questo valore perchè la distanza viene calcolata dal centro dell'auto del traffico
                        bool   sottoDistanzaSicurezza  = (distanzaSicurezzaUpdate - hitInfo.distance) > 1f;
                        bool   piuVeloceDelTarget      = (miaVelocita - velocitaTarget) >= 1f;
                        if ((piuVeloceDelTarget || sottoDistanzaSicurezza))
                        {
                            if (autoDavanti == false)
                            {
                                if (sottoDistanzaSicurezza)
                                {
                                    distanzaSicurezza = distanzaSicurezzaUpdate;
                                }
                                else
                                {
                                    distanzaSicurezza = (Math.Pow((frontSpeed * 3.6f / 10f), 2) + 5f);
                                }

                                autoDavanti = true;
                                distanzaInizialeSicurezza = hitInfo.distance;
                                velocitàInizialeSicurezza = this.GetComponent <Rigidbody>().velocity.magnitude;
                            }
                        }
                        else
                        {
                            autoDavanti = false;
                        }

                        if (Math.Abs(hitInfo.distance - distanzaSicurezza) >= 1f && autoDavanti && miaVelocita > 0.1f)
                        {
                            /* se Vf è la velocita finale, Vi quella iniziale, Df la distanza finale, Di la distanza iniziale, Dc la distanza corrente
                             * allora Vx = (Vf + Vi) / ((Df + Di)/Dc)*/
                            targetSpeed = (velocitaTarget + velocitàInizialeSicurezza) / (((float)distanzaSicurezza + distanzaInizialeSicurezza) / hitInfo.distance);
                        }
                        else
                        {
                            autoDavanti = false;
                            targetSpeed = velocitaTarget;
                        }
                    }
                }
                if (hitInfo.rigidbody.gameObject.layer.Equals(12))
                {
                    float  distanza      = Vector3.Distance(transform.position, hitInfo.rigidbody.transform.position);
                    double spazioFrenata = (Math.Pow(GetComponent <Rigidbody>().velocity.magnitude, 2)) / (2 * 2.3f);
                    if (spazioFrenata > distanza)
                    {
                        evitare = true;
                    }
                    else
                    {
                        inchiodare = true;
                    }
                }
            }
            else
            {
                evitare = inchiodare = false;

                if (currentNode.isInintersection)
                {
                    targetSpeed = 4f;
                }
                else
                {
                    targetSpeed = maxSpeed;
                }
            }
        }
        else
        {
            evitare = inchiodare = false;

            if (currentNode.isInintersection)
            {
                targetSpeed = 4f;
            }
            else
            {
                targetSpeed = maxSpeed;
            }
        }


        Debug.DrawLine(transform.position, target);
        //STEER CAR
        Vector3 steerVector = new Vector3(normal.x, transform.position.y, normal.z) - transform.position;

        m_targetSteer = Vector3.SignedAngle(transform.forward, normal - transform.position, Vector3.up);

        float differenza       = Math.Abs(m_targetSteer) - Math.Abs(m_targetSteer_precedente);
        float differenzaTarget = Math.Abs(m_targetSteer - m_targetSteer_target);

        if (differenza <= 0.2f || (m_targetSteer_target != 0 && differenzaTarget > 0.2f))
        {
            if ((m_targetSteer_precedente < 0 && m_targetSteer > 0) || (m_targetSteer_precedente > 0 && m_targetSteer < 0) || m_targetSteer_target != 0)
            {
                if (m_targetSteer_target == 0)
                {
                    m_targetSteer_target = m_targetSteer;
                }
                else
                {
                }
                m_targetSteer            = Mathf.Lerp(m_targetSteer_precedente, m_targetSteer_target, steerSpeed * Time.fixedDeltaTime);
                m_targetSteer_precedente = m_targetSteer;
            }
            else
            {
                m_targetSteer            = m_targetSteer_precedente;
                m_targetSteer_precedente = m_targetSteer;
            }
        }

        PIDControllerSterzata.pFactor = _pidPars.p_sterzataPCH;
        PIDControllerSterzata.iFactor = _pidPars.i_sterzataPCH;
        PIDControllerSterzata.dFactor = _pidPars.d_sterzataPCH;
        if (sbacchettamentoEvitabile)
        {
            PIDControllerSterzata.dFactor = 0f;
        }
        else
        {
            PIDControllerSterzata.dFactor = 0.3f;
            //if (sbacchettamentoForte)
            //{
            //    PIDControllerSterzata.dFactor = 0.3f;

            //}
            //else
            //{
            //    PIDControllerSterzata.dFactor = 0.3f;
            //}
        }


        float turnPrecedente = vehicleController.steerInput * 45f;

        float steeringAngle = PIDControllerSterzata.UpdatePars(m_targetSteer, turnPrecedente, Time.fixedDeltaTime);

        //float steeringAngle = m_targetSteer;

        //Limit the steering angle
        steeringAngle = Mathf.Clamp(steeringAngle, -45, 45);

        float differenzaTurn = Math.Abs(steeringAngle - turnPrecedente);

        averageSteeringAngle = averageSteeringAngle + ((steeringAngle - averageSteeringAngle) / _pidPars.indiceSterzataCurva);
        if (Mathf.Abs(averageSteeringAngle - turnPrecedente) <= _pidPars.puntoMortoSterzata)
        {
            averageSteeringAngle = turnPrecedente;
        }

        averageSteeringAngle = Mathf.Clamp(Mathf.Lerp(turnPrecedente, averageSteeringAngle, steerSpeed * Time.fixedDeltaTime), -45f, 45f);


        vehicleController.steerInput = averageSteeringAngle / 45f;
        //vehicleController.steerInput = steeringAngle / 45f;
        //FINE STEERCAR


        if (averageSteeringAngle > 5f || averageSteeringAngle < -5f)
        {
            //targetSpeed = targetSpeed * Mathf.Clamp(1 - (currentTurn / maxTurn), 0.1f, 1f);
            targetSpeed = targetSpeed * Mathf.Clamp(1 - (Math.Abs(averageSteeringAngle) / 45), 0.2f, 1f);
        }

        MoveCarUtenteAccelerazione();
    }
示例#4
0
    void EnvironmentDetect()
    {
        LayerMask mask = (1 << LayerMask.NameToLayer("Traffic")) | (1 << LayerMask.NameToLayer("obstacle")) | (1 << LayerMask.NameToLayer("EnvironmentProp")) | (1 << LayerMask.NameToLayer("Signage")); //restrict OverlapSphere only to the layers of interest

        Collider[]          colls    = Physics.OverlapSphere(gameObject.transform.position, 50.0f, mask);
        HashSet <Transform> curColls = new HashSet <Transform>(); //this is to store the root transform of the colliders returned by OverlapSphere

        Timer -= Time.deltaTime;                                  //thanks to this timer cubes and tags are instantiated only every 0.1 ms
        if (Timer <= 0f)
        {
            foreach (KeyValuePair <GameObject, GameObject> pair in cubesAndTags)
            {
                Destroy(pair.Key);
                Destroy(pair.Value);
                //Debug.Log("destroyed" + g + "update is: " + i);
            }
            cubesAndTags.Clear();

            foreach (Collider c in colls)
            {
                switch (c.gameObject.layer)
                {
                case 16:
                {         //EnvironmentProp: remember that when you instantiate using transform.position it refers to the pivot and not to the center of the mesh; //so if there is still an offset between the bounding cube and the mesh is due to the pivot point
                    Bounds bounds = new Bounds();
                    if (c.transform.tag.Equals("Tree"))
                    {
                        CapsuleCollider capsCol = c as CapsuleCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * new Vector3(capsCol.center.x * c.transform.localScale.x, capsCol.center.y * c.transform.localScale.y, capsCol.center.z * c.transform.localScale.z);
                        bounds.size   = new Vector3(capsCol.radius * 2.0f * c.transform.localScale.x, capsCol.radius * 2.0f * c.transform.localScale.y, capsCol.height * c.transform.localScale.z);

                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;         //infoTag offset
                        traslL = new Vector3(traslL.x * 0.5f + 2.0f, 0, 0);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);
                        Debug.Log(c.transform.name + ", " + traslL);
                        float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 10.0f)
                        {
                            infos[0] = "0";         //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString();
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], infos));
                        }
                    }
                    else if (c.transform.tag.Equals("Rock"))
                    {
                        SphereCollider sphereCol = c as SphereCollider;
                        bounds.center = Quaternion.Euler(c.transform.localEulerAngles) * new Vector3(sphereCol.center.x * c.transform.localScale.x, sphereCol.center.y * c.transform.localScale.y, sphereCol.center.z * c.transform.localScale.z);
                        bounds.size   = new Vector3(sphereCol.radius * 2.0f * c.transform.localScale.x, sphereCol.radius * 2.0f * c.transform.localScale.y, sphereCol.radius * 2.0f * c.transform.localScale.z);

                        Vector3 traslL = Quaternion.Euler(c.transform.localEulerAngles) * bounds.size;         //infoTag offset
                        traslL = new Vector3(traslL.x * 0.5f + 2.0f, traslL.y * 0.5f, 0);
                        Vector3 traslR = new Vector3(-traslL.x, traslL.y, traslL.z);
                        float   dist   = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                        if (dist <= 10.0f)
                        {
                            infos[0] = "0";         //speed of EnvironmentProp is null
                            infos[1] = Mathf.RoundToInt(dist).ToString();
                            infos[2] = "";
                            cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), CreateInfoTag(c.transform.position + bounds.center, traslL, traslR, sprites[28], infos));
                        }
                    }
                }
                break;

                case 17:
                {         //Signage
                    Bounds      bounds = new Bounds();
                    BoxCollider boxCol = c as BoxCollider;
                    bounds.center = boxCol.center;
                    bounds.size   = boxCol.size * 1.25f;
                    float dist = CalculateDistance(rayCastPos.position, c.transform.position + bounds.center);
                    infos[0] = "0";         //speed of EnvironmentProp is null
                    infos[1] = Mathf.RoundToInt(dist).ToString();
                    infos[2] = "";
                    cubesAndTags.Add(CreateBoundingCube(c.transform, c.transform.position + bounds.center, bounds.size), new GameObject());
                }
                break;

                case 12:
                {          //obstacle
                    Bounds bounds = ComputeBounds(c.transform);
                    infos[0] = Mathf.RoundToInt(CalculateObstacleSpeed(c.transform)).ToString();
                    infos[1] = Mathf.RoundToInt(CalculateDistance(rayCastPos.position, bounds.center)).ToString();
                    infos[2] = "";
                    //cubesAndTags.Add(CreateBoundingCube(c.transform, bounds.center, bounds.size), CreateInfoTag(bounds.center, bounds.size, sprites[28], infos));
                }
                break;

                case 8:
                {           //Traffic
                    if (!curColls.Contains(c.transform.root))
                    {       //this is in order to check if an object has more colliders than one; if so, one is sufficient so simply discard other otherwise the cube instantiated would be equal to the number of colliders
                        Bounds  bounds  = ComputeBounds(c.transform.root);
                        TrafPCH trafPCH = c.transform.root.GetComponent <TrafPCH>();
                        if (trafPCH != null)
                        {
                            float speed = trafPCH.currentSpeed;
                            infos[0] = Mathf.RoundToInt(speed * 3.6f).ToString();
                            infos[1] = Mathf.RoundToInt(CalculateDistance(rayCastPos.position, bounds.center)).ToString();
                            infos[2] = "";
                            //cubesAndTags.Add(CreateBoundingCube(c.transform.root, bounds.center, bounds.size), CreateInfoTag(bounds.center, bounds.size, sprites[0], infos));
                            curColls.Add(c.transform.root);
                        }
                    }
                }
                break;
                }
            }
            Timer = 0.1f;
        }
        //i++;
    }
示例#5
0
    void EnvironmentDetect()
    {
        List <CubesAndTags> objectsList = new List <CubesAndTags>(IDsAndGos.Values);

        for (int i = 0; i < objectsList.Count; i++)
        {
            if (objectsList[i].other != null)
            {
                float dist = CalculateDistance(rayCastPos.position, objectsList[i].other.transform.position); //this distance does not include bounds since it cannot always be precomputed, for example, this is the case of moving objects

                switch (objectsList[i].other.gameObject.layer)
                {
                case 16:
                {
                    Bounds bounds = objectsList[i].bounds[0];
                    Sprite sprite = objectsList[i].other.GetComponent <Image>().sprite;
                    if (BOUNDINGCUBE)
                    {
                        riskAssessment.BoundingCubeLerperPCH(objectsList[i], bounds, sprite, ReturnTrasl(bounds, objectsList[i].other), 0);
                    }
                    //else
                    //    riskAssessment.InfoTagWarn(objectsList[i], bounds, sprite, ReturnTrasl(bounds, objectsList[i].other), 0);
                }
                break;

                case 17:     //Signage
                {
                    float    dotProduct = Vector3.Dot(gameObject.transform.TransformDirection(Vector3.forward), objectsList[i].other.transform.TransformDirection(Vector3.up));
                    Animator anim       = objectsList[i].infoTag[0].GetComponent <Animator>();
                    if (dotProduct >= -1 && dotProduct <= -0.707f)
                    {
                        Bounds bounds      = objectsList[i].bounds[0];
                        int    spriteIndex = CSVSignDictionary[objectsList[i].other.name];
                        objectsList[i].boundingCube[0].GetComponent <Renderer>().enabled = true;
                        objectsList[i].infoTag[0].GetComponent <Canvas>().enabled        = true;
                        UpdateInfoTag(objectsList[i], bounds, "", ResourceHandler.instance.sprites[spriteIndex], dist, Vector3.zero, 0);

                        if (objectsList[i].other.transform.name.Equals("StopSign") || objectsList[i].other.transform.parent.name.Equals("SpeedLimit") || objectsList[i].other.transform.parent.name.Equals("FallenRocksSign"))
                        {
                            if (dist <= 40)
                            {
                                anim.SetBool("Blink", true);
                            }
                            else
                            {
                                anim.SetBool("Blink", false);
                            }
                        }
                    }
                    else
                    {
                        objectsList[i].boundingCube[0].GetComponent <Renderer>().enabled = false;
                        objectsList[i].infoTag[0].GetComponent <Canvas>().enabled        = false;

                        if (objectsList[i].other.transform.name.Equals("StopSign") || objectsList[i].other.transform.parent.name.Equals("SpeedLimit") || objectsList[i].other.transform.parent.name.Equals("FallenRocksSign"))
                        {
                            anim.SetBool("Blink", false);
                        }
                    }
                }
                break;

                case 12:
                {
                    Bounds bounds = objectsList[i].bounds[0];
                    Sprite sprite = objectsList[i].other.GetComponent <Image>().sprite;
                    if (/*BOUNDINGCUBE*/ !objectsList[i].other.CompareTag("Rock"))
                    {
                        riskAssessment.BoundingCubeLerperObstaclePCH(objectsList[i], bounds, CalculateObstacleSpeed(objectsList[i].other.transform), 0, sprite, Vector3.zero, 0);
                    }
                    else
                    {
                        riskAssessment.BoundingCubeLerperDangerousCarPCH(objectsList[i], bounds, 0, ResourceHandler.instance.visualisationVars.obstacleDistToWarn, 25f, sprite, Vector3.zero, 0);         //Rock uses pure distance evaluation for danger
                    }
                }
                break;

                case 8:
                {
                    Debug.DrawLine(objectsList[i].other.transform.position, rayCastPos.position, Color.green);
                    Bounds  bounds  = objectsList[i].bounds[0];
                    TrafPCH trafPCH = objectsList[i].other.transform.root.GetComponent <TrafPCH>();
                    if (trafPCH != null)
                    {
                        float  speed        = trafPCH.currentSpeed;
                        float  acceleration = trafPCH.accelerazione;
                        Sprite sprite       = objectsList[i].other.GetComponent <Image>().sprite;
                        if (/*BOUNDINGCUBE*/ objectsList[i].other.transform.root.CompareTag("DangerousCar"))
                        {
                            if (trafPCH.currentWaypointIndex < 1970)         //overtaking Car
                            {
                                riskAssessment.BoundingCubeLerperDangerousCarPCH(objectsList[i], bounds, speed, ResourceHandler.instance.visualisationVars.obstacleDistToWarn, 25f, sprite, Vector3.zero, 0);
                            }
                            else
                            {
                                riskAssessment.BoundingCubeLerperDangerousCarPCH(objectsList[i], bounds, speed, ResourceHandler.instance.visualisationVars.DangerousCarDistToWarn, 25f, sprite, Vector3.zero, 0);
                            }
                        }
                        //riskAssessment.BoundingCubeLerperPCH(objectsList[i], bounds, speed, acceleration, sprite, Vector3.zero, 0);
                        else
                        {
                            riskAssessment.BoundingCubeLerperPCH(objectsList[i], bounds, speed, acceleration, sprite, Vector3.zero, 0);
                        }
                    }
                }
                break;
                }
            }
        }
    }