// Use this for initialization
 void Start()
 {
     roads                       = new List <ERRoad> ();
     roadNetwork                 = new ERRoadNetwork();
     roadType                    = new ERRoadType();
     roadType.roadWidth          = 6;
     roadType.roadMaterial       = Resources.Load("Materials/roads/single lane") as Material;
     roadType.connectionMaterial = Resources.Load("Materials/crossings/crossing material") as Material;
 }
    void Start()
    {
        Debug.Log("Please read the comments at the top before using the runtime API!");

        // Create Road Network object
        roadNetwork = new ERRoadNetwork();

        // Create road
        //	ERRoad road = roadNetwork.CreateRoad(string name);
        //	ERRoad road = roadNetwork.CreateRoad(string name, Vector3[] markers);
        //	ERRoad road = roadNetwork.CreateRoad(string name, ERRoadType roadType);
        //	ERRoad road = roadNetwork.CreateRoad(string name, ERRoadType roadType, Vector3[] markers);

        ERRoadType roadType = new ERRoadType();

        roadType.roadWidth    = 6;
        roadType.roadMaterial = Resources.Load("Materials/roads/single lane") as Material;

        Vector3[] markers = new Vector3[4];
        markers[0] = new Vector3(200, 5, 200);
        markers[1] = new Vector3(250, 5, 200);
        markers[2] = new Vector3(250, 5, 250);
        markers[3] = new Vector3(300, 5, 250);

        road = roadNetwork.CreateRoad("road 1", roadType, markers);

        // Add Marker: ERRoad.AddMarker(Vector3);
        road.AddMarker(new Vector3(300, 5, 300));

        // Add Marker: ERRoad.InsertMarker(Vector3);
        road.InsertMarker(new Vector3(275, 5, 235));

        // Delete Marker: ERRoad.DeleteMarker(int index);
        road.DeleteMarker(2);

        // Set the road width : ERRoad.SetWidth(float);
        //	road.SetWidth(10);

        // Set the road material : ERRoad.SetMaterial(Material);
        //	Material mat = Resources.Load("Materials/roads/single lane") as Material;
        //	road.SetMaterial(mat);

        // Build Road Network
        roadNetwork.BuildRoadNetwork();

        // Restore Road Network
        //	roadNetwork.RestoreRoadNetwork();


        // create dummy object
        go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    }
Beispiel #3
0
    /// <summary>
    /// Methode zum Zeichnen einer geraden Straße.
    /// </summary>
    /// <param name="length">Die Länge der Straße.</param>
    /// <param name="minCars">Die minimale Anzahl der Autos auf dem Straßenteil.</param>
    /// <param name="maxCars">Die maximale Anzahl der Autos auf dem Straßenteil.</param>
    /// <param name="heightDifference">Der Höhenunterschied.</param>
    /// <param name="seed">Der Seed.</param>
    /// <returns>Die Straße.</returns>
    public ERRoad CreateStraight(float length, int minCars, int maxCars, float?heightDifference, string seed)
    {
        // Die Strecke neu holen
        this.network = new ERRoadNetwork();
        this.network.BuildRoadNetwork();

        // Den RoadType holen
        ERRoadType roadType = this.GetRandomRoadType();

        // Hole die akutellen Streckenteile
        ERRoad[] currentRoads = network.GetRoads();

        // Hole die Höhe der Strecke
        float fixHeightDifference = heightDifference ?? 0;

        // Lege die Positionen der Strecke an
        Vector3 startPosition  = new Vector3(0, 0, 0);
        Vector3 middlePosition = new Vector3(0, fixHeightDifference / 2, length / 2);
        Vector3 endPosition    = new Vector3(0, fixHeightDifference, length);

        ERRoad lastRoad = null;
        ERRoad road     = null;

        if (currentRoads.Length > 0)
        {
            // Hole die letzte Strecke
            lastRoad = currentRoads.Last();

            // Hole den letzten Punkt der Strecke
            Vector3[] markers    = lastRoad.GetMarkerPositions();
            Vector3   lastMarker = markers.Last();

            // Die richtige Rotation ausrechnen
            Vector3 heading   = (lastMarker - markers[markers.Length - 2]);
            Vector3 direction = heading / heading.magnitude;
            direction.y = 0;

            // Das Verhältnis zwischen x und z-Achse ausrechnen
            float x = direction.x / (direction.magnitude);
            float z = direction.z / (direction.magnitude);

            Vector3[] streetVectors = new Vector3[(int)length];
            float     heightPart    = fixHeightDifference / length;
            for (int lengthPart = 0; lengthPart < length; lengthPart++)
            {
                streetVectors[lengthPart] = lastMarker + new Vector3(x * lengthPart, heightPart * lengthPart, z * lengthPart);
            }

            // Generiere Straße
            road = network.CreateRoad("Straight" + currentRoads.Length, roadType, streetVectors);
        }
        else
        {
            // Generiere erste Straße
            road = network.CreateRoad("Straight" + currentRoads.Length, roadType, new Vector3[] { startPosition, middlePosition, endPosition });
        }

        // Erstelle die Strecke mit einem eindeutigen Namen
        customEasyRoads.Add(new CustomEasyRoad(car, road, minCars, maxCars, numberOfTracks));
        return(road);
    }
Beispiel #4
0
    /// <summary>
    /// Erstellt eine Kurve anhand eines Winkels, der Länge der Kurve und den Positionen des aktuellen und vorherigen Straßen Elementes.
    /// </summary>
    /// <param name="angle">Der Winkel.</param>
    /// <param name="length">Die Länge des Straßenelementes.</param>
    /// <param name="heightDifference">Die Höhendifferenz für den Streckenabschnitt.</param>
    /// <param name="minCars">Die minimale Anzahl an Autos auf diesem Streckenabschnitt.</param>
    /// <param name="maxCars">Die maximale Anzahl an Autos auf diesem Streckenabschnitt.</param>
    /// <param name="seed">Der Seed des Random-Generators.</param>
    /// <returns>Die Kurve.</returns>
    public ERRoad CreateCurve(float angle, float length, float?heightDifference, int minCars, int maxCars, string seed)
    {
        // Die Strecke neu holen
        this.network = new ERRoadNetwork();
        this.network.BuildRoadNetwork();

        // hole die Höhendifference
        float fixHeightDifference = heightDifference ?? 0f;

        // Die StartPosition initialisieren.
        Vector3 startPosition = new Vector3(0, 0, 0);

        // Die Ausrichtung initialisieren (default ist z-Richtung).
        Vector3 heading = new Vector3(0, 0, 1);

        // Den RoadType holen
        ERRoadType roadType = this.GetRandomRoadType();

        // Hole die Position des letzten Streckenabschnitts, wenn vorhanden.
        ERRoad lastRoad = null;

        if (network.GetRoads().Length > 0)
        {
            lastRoad = network.GetRoads().Last();
            Vector3[] markers      = lastRoad.GetMarkerPositions();
            Vector3   lastPosition = markers.Last();

            // Die Startposition an den letzten Streckenabschnitt anpassen.
            startPosition = lastPosition;

            // Die Ausrichtung in Bezug auf den vorherigen Streckenabschnitt holen.
            Vector3 secondToLast = markers[markers.Count() - 2];
            heading   = lastPosition - secondToLast;
            heading.y = 0;
        }

        // Den (geraden) Richtungsvektor berechnen.
        Vector3 direction = heading / heading.magnitude;

        // Der Vektor der y-Achse
        Vector3 yAxis = new Vector3(0, 1, 0);

        // Die Anzahl an zu berechnenden Positionen für die Kurve
        int   numbPositions      = Convert.ToInt32(Math.Abs(angle));
        float positionPercentage = numbPositions * percentageEven;

        // Das Array mit den neuen Positionen.
        Vector3[] curvePositions = new Vector3[numbPositions];
        curvePositions[0] = startPosition;

        // es werden in 1-Grad-Schritten Positionen berechnet.
        float anglePart  = angle / Math.Abs(angle);
        float lengthPart = length / numbPositions;
        float heightPart = fixHeightDifference / (numbPositions - (2 * positionPercentage));

        // Die Positionen berechnen.
        for (int i = 1; i < numbPositions; i++)
        {
            // Die direction für den nächsten Schritt berechnen
            if (i > 1)
            {
                heading   = curvePositions[i - 1] - curvePositions[i - 2];
                heading.y = 0;
                direction = heading / heading.magnitude;
            }

            // Die letzte Position holen.
            Vector3 oldPosition = curvePositions[i - 1];

            // innerhalb des Prozent-Bereiches die Höhe anwenden.
            if (i > positionPercentage && i < (numbPositions - positionPercentage))
            {
                oldPosition.y += heightPart.Truncate(5);
            }

            // Die neue Position berechnen.
            curvePositions[i] = oldPosition + Quaternion.AngleAxis(anglePart, yAxis) * direction * lengthPart;
        }

        // Die Kurve erzeugen.
        ERRoad thisRoad = this.network.CreateRoad("Curve" + network.GetRoads().Count(), roadType, curvePositions);

        customEasyRoads.Add(new CustomEasyRoad(car, thisRoad, minCars, maxCars, numberOfTracks));
        return(thisRoad);
    }
    void Start()
    {
        Debug_Log.Call_WriteLog("Please read the comments at the top of the runtime script (/Assets/EasyRoads3D/Scripts/runtimeScript) before using the runtime API!");

        // Create Road Network object
        roadNetwork = new ERRoadNetwork();

        // Create road
        //	ERRoad road = roadNetwork.CreateRoad(string name);
        //	ERRoad road = roadNetwork.CreateRoad(string name, Vector3[] markers);
        //	ERRoad road = roadNetwork.CreateRoad(string name, ERRoadType roadType);
        //	ERRoad road = roadNetwork.CreateRoad(string name, ERRoadType roadType, Vector3[] markers);

        // get exisiting road types
        //  ERRoadType[] roadTypes = roadNetwork.GetRoadTypes();
        //  ERRoadType roadType = roadNetwork.GetRoadTypeByName(string name);


        // create a new road type
        ERRoadType roadType = new ERRoadType();

        roadType.roadWidth    = 6;
        roadType.roadMaterial = Resources.Load("Materials/roads/road material") as Material;
        // optional
        roadType.layer = 1;
        roadType.tag   = "Untagged";
        //   roadType.hasMeshCollider = false; // default is true

//		roadType = roadNetwork.GetRoadTypeByName("Train Rail");
//		Debug_Log.Call_WriteLog(roadType.roadMaterial);

        // create a new road
        Vector3[] markers = new Vector3[4];
        markers[0] = new Vector3(200, 5, 200);
        markers[1] = new Vector3(250, 5, 200);
        markers[2] = new Vector3(250, 5, 250);
        markers[3] = new Vector3(300, 5, 250);

        road = roadNetwork.CreateRoad("road 1", roadType, markers);

        // road.SetResolution(float value):void;


        // Add Marker: ERRoad.AddMarker(Vector3);
        road.AddMarker(new Vector3(300, 5, 300));

        // Add Marker: ERRoad.InsertMarker(Vector3);
        road.InsertMarker(new Vector3(275, 5, 235));
        //  road.InsertMarkerAt(Vector3 pos, int index): void;

        // Delete Marker: ERRoad.DeleteMarker(int index);
        road.DeleteMarker(2);


        // Set the road width : ERRoad.SetWidth(float width);
        //	road.SetWidth(10);

        // Set the road material : ERRoad.SetMaterial(Material path);
        //	Material mat = Resources.Load("Materials/roads/single lane") as Material;
        //	road.SetMaterial(mat);

        // add / remove a meshCollider component
        //   road.SetMeshCollider(bool value):void;

        // set the position of a marker
        //   road.SetMarkerPosition(int index, Vector3 position):void;
        //   road.SetMarkerPositions(Vector3[] position):void;
        //   road.SetMarkerPositions(Vector3[] position, int index):void;

        // get the position of a marker
        //   road.GetMarkerPosition(int index):Vector3;

        // get the position of a marker
        //   road.GetMarkerPositions():Vector3[];

        // Set the layer
        //   road.SetLayer(int value):void;

        // Set the tag
        //   road.SetTag(string value):void;

        // set marker control type
        //  road.SetMarkerControlType(int marker, ERMarkerControlType type) : bool; // Spline, StraightXZ, StraightXZY, Circular

        // find a road
        //  public static function ERRoadNetwork.GetRoadByName(string name) : ERRoad;

        // get all roads
        //  public static function ERRoadNetwork.GetRoads() : ERRoad[];

        // snap vertices to the terrain (no terrain deformation)
//		road.SnapToTerrain(true);

        // Build Road Network
        roadNetwork.BuildRoadNetwork();

        // remove script components
//		roadNetwork.Finalize();

        // Restore Road Network
        //	roadNetwork.RestoreRoadNetwork();

        // Show / Hide the white surfaces surrounding roads
        //     public function roadNetwork.HideWhiteSurfaces(bool value) : void;

        //   road.GetConnectionAtStart(): GameObject;
        //   road.GetConnectionAtStart(out int connection): GameObject; // connections: 0 = bottom, 1= tip, 2 = left, 3 = right (the same for T crossings)

        //   road.GetConnectionAtEnd(): GameObject;
        //   road.GetConnectionAtEnd(out int connection): GameObject; // connections: 0 = bottom, 1= tip, 2 = left, 3 = right (the same for T crossings)

        // Snap the road vertices to the terrain following the terrain shape (no terrain deformation)
        //   road.SnapToTerrain(bool value): void;
        //   road.SnapToTerrain(bool value, float yOffset): void;

        // get the road length
        //   road.GetLength() : float;

        // create dummy object
        go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    }
    private void SetNodes(Transform parent)
    {
        try
        {
            //Problem in that the loop is finding itself
            //This avoids recursing a folder that was created by this process
            if (parent.name.Contains(nodeFolderName))
            {
                return;
            }

            //TODO: will need to check for the preexisting nodes, and delete them
            //   "Traffic Nodes Right Lane(0)"


            bool   isRight  = true;
            string sSide    = "Right";
            string roadName = parent.parent.name;

            //Hack: use the name to determine if this is the Right or Left hand side
            if (parent.name.ToLower().Contains("left"))
            {
                isRight = false;
                sSide   = "Left";
            }

            //Get width of road, to get the number of lanes
            ERRoad           erRoad       = roadNetwork.GetRoadByName(roadName);
            ERRoadType       roadType     = erRoad.GetRoadType();
            float            roadWidth    = roadType.roadWidth;
            byte             laneCount    = System.Convert.ToByte((roadType.roadWidth / 2) / laneWidth);
            List <Transform> trafficNodes = new List <Transform>();
            Transform        nodeChild;


            for (byte b = 0; b < laneCount; b++)
            {
                string folderName = nodeFolderName + " " + sSide + " Lane (" + b.ToString() + ")";


                //todo NOT FINDING IT WHEN IT IS INDEED there
                Transform tempFolder = parent.parent.Find(folderName);

                //Check for the existance of this folder, if it already exists, delete it.
                //The road has been adjusted and it is safer to assume that the old nodes are no longer correct
                //...just in case
                if (tempFolder != null)
                {
                    GameObject.DestroyImmediate(tempFolder.gameObject);
                }

                GameObject folder = new GameObject(folderName);

                if (b == 0)
                {
                    //Remove existing Traffic Nodes from the folder that they were created
                    //Moving them insures that they are not moved again, in a forever recursive loop
                    //and to know they are completed, and not readjusted.
                    if (isRight)
                    {
                        for (int i = 0; i < parent.childCount; i++)
                        {
                            //NOTE: Be aware that when creating the Side Object the "Combine Objects" checkbox MUST be unchecked
                            //      otherwise a few of these children will not be TrafficSystemNodes and that will cause all sorts of issues.
                            nodeChild      = parent.GetChild(i);
                            nodeChild.name = roadName + " " + sSide + " node (" + i + ")";
                            trafficNodes.Add(nodeChild);
                        }
                    }
                    else
                    {
                        int iLoop = 0;
                        for (int i = (parent.childCount - 1); i > -1; i--)
                        {
                            nodeChild      = parent.GetChild(i);
                            nodeChild.name = roadName + " " + sSide + " node (" + iLoop + ")";
                            trafficNodes.Add(nodeChild);

                            iLoop++;
                        }
                    }

                    //Add to new parent
                    foreach (Transform trafficNode in trafficNodes)
                    {
                        trafficNode.SetParent(folder.transform);
                    }

                    //Connect node to it's next neighbor
                    ConnectNodes(folder);
                }
                else
                {
                    // PROCESS
                    // * Create new nodes
                    // * Place them
                    // * Connect them to each other - still a bit of an issue here

                    //TODO
                    // * Connect them to the previous Lane
                    // * Connect previous lane to this lane

                    //Create the nodes and place them
                    for (int i = 0; i < trafficNodes.Count; i++)
                    {
                        float nodePosition = this.laneWidth;
                        if (isRight)
                        {
                            nodePosition = -(this.laneWidth);
                        }

                        Transform trafficNode = Instantiate(trafficNodeInstance, trafficNodes[i].position + trafficNodes[i].right * nodePosition, trafficNodes[i].rotation);
                        trafficNode.gameObject.isStatic = true;
                        trafficNode.name = roadName + " " + sSide + " node (" + i + ")";
                        trafficNode.SetParent(folder.transform);



                        //Connect to previous lane

                        //trafficNodes[i] = trafficNode;

                        //TODO: connect to next node, BUT this hasn't been created yet so....
                        //Do I need another LIST?  Do I update the current list with the new Node, then in a separate loop connect them?
                        //if (i < (folder.transform.childCount - 1))
                        //{
                        //    TrafficSystemNode nextNode = folder.transform.GetChild(i + 1).GetComponent<TrafficSystemNode>();

                        //    folder.transform.GetChild(i).GetComponent<TrafficSystemNode>().m_connectedChangeLaneNodes.Clear(); //To insure that previous values are removed
                        //    folder.transform.GetChild(i).GetComponent<TrafficSystemNode>().m_connectedChangeLaneNodes.Add(nextNode);
                        //}
                    }


                    //folder.transform.SetParent(parent.parent);

                    //Connect node to it's next neighbor
                    ConnectNodes(folder);


                    //Connect to Previous nodes to Current nodes
                    folderName = nodeFolderName + " " + sSide + " Lane (" + (b - 1).ToString() + ")";
                    GameObject previousFolder = parent.parent.Find(folderName).gameObject;
                    ConnectLanes(folder, previousFolder);
                }

                folder.transform.SetParent(parent.parent);
            }

            //DestroyImmediate(parent.gameObject);  //Remove the original folder, causes an issue with the loop

            //TODO: intersections (someday)
        }
        catch (System.Exception ex)
        {
            HBCLogging.logException(ex);
        }
    }