Exemplo n.º 1
0
    //Creates Trees beside the road with "density".
    public static void Create(VertexPath path, float density)
    {
        float length = path.length;

        float distInterval = length / density;

        for (int i = 0; i < density; i++)
        {
            Vector3 offset = Vector3.right * 28f;
            Vector3 pos    = path.GetPointAtDistance(distInterval * i) + Vector3.forward * Random.Range(-5f, 5f);

            int rand = Random.Range(1, 5);
            for (int j = 0; j < rand; j++)
            {
                offset.x += j * 10f;
                pos      += offset;
                Instantiate(instance.Tree, pos, Quaternion.identity);
            }

            rand   = Random.Range(1, 5);
            offset = Vector3.left * 28f;
            pos    = path.GetPointAtDistance(distInterval * i) + Vector3.forward * Random.Range(-5f, 5f);

            for (int j = 0; j < rand; j++)
            {
                offset.x += -j * 10f;
                pos      += offset;
                Instantiate(instance.Tree, pos, Quaternion.identity);
            }
        }
    }
Exemplo n.º 2
0
    private void GenerateLeaves()
    {
        lastLeafPosition.Clear();
        lastLeafRotation.Clear();
        foreach (Transform child in Leaves.transform)
        {
            GameObject.Destroy(child.gameObject);
        }

        for (int i = 0; i < LeafAmount; ++i)
        {
            GameObject leaf = Instantiate(LeafPrefab, Leaves.transform);

            Vector3 tempPosition = stemPath.GetPointAtDistance(1f / LeafAmount * i * 10);
            Vector3 tempRotation = stemPath.GetNormalAtDistance(1f / LeafAmount * i * 10);

            leaf.transform.position = tempPosition;
            float normalAngle = Vector3.Angle(tempRotation, Vector3.right);
            normalAngle = tempRotation.y > 0 ? normalAngle : -normalAngle;
            float[] currAngle = new float[] { Random.Range(0, 360), normalAngle };
            leaf.transform.Rotate(new Vector3(0, currAngle[0], currAngle[1]));

            lastLeafPosition.Add(tempPosition);
            lastLeafRotation.Add(currAngle);
        }
        lastLeafAmount = LeafAmount;
        stemPath       = StemSpline.GetComponent <PathCreator>().path;
    }
Exemplo n.º 3
0
        private void UpdateBallPosition(float distanceTraveled)
        {
            var pathPointPosition = _path.GetPointAtDistance(distanceTraveled + _config.StartOffset.Value);
            var pathPointRotation = _path.GetRotationAtDistance(distanceTraveled + _config.StartOffset.Value);

            var position       = pathPointPosition + Vector3.up * 0.5f + Vector3.right * _onRoadPos * 2f;
            var rotationAngles = new Vector3(
                transform.rotation.eulerAngles.x,
                pathPointRotation.eulerAngles.y,
                transform.rotation.eulerAngles.z);

            transform.SetPositionAndRotation(position, Quaternion.Euler(rotationAngles));
            Position = position;
        }
Exemplo n.º 4
0
    void Update()
    {
        _distanceTravelled += _speed * Time.deltaTime;

        var travelPercent = _distanceTravelled / _path.length;

        if (travelPercent > _startToFleePercent)
        {
            _startToFleeParticle.gameObject.SetActive(true);
        }

        if (travelPercent >= 1f)
        {
            OnDuckFlee?.Invoke(this);
            _OnDuckFlee.Invoke();

            Destroy(gameObject);
            return;
        }

        transform.position = _path.GetPointAtDistance(_distanceTravelled);
        var forward = _path.GetDirectionAtDistance(_distanceTravelled);
        var rot     = Quaternion.LookRotation(forward, Vector3.up);

        transform.rotation = rot;
    }
Exemplo n.º 5
0
        void Generate()
        {
            if (pathCreator != null && CheckPrefabArray() != false && planksHolder != null)
            {
                DestroyObjects();

                VertexPath path = pathCreator.path;

                spacing = Mathf.Max(minSpacing, spacing);
                float dst = 0;

                while (dst < path.length)
                {
                    Vector3    point = path.GetPointAtDistance(dst);
                    Quaternion rot   = path.GetRotationAtDistance(dst);
                    Instantiate(prefabArray[Random.Range(0, prefabArray.Length)], point, rot, planksHolder.transform);
                    dst += spacing;
                }

                /*if (anchorPrefab != null && anchorsHolder != null)
                 * {
                 *      AddAnchor(0.0f, anchorSpacing , -anchorOffset);
                 *      // TODO : Looking at the source code, if the distance is 0 or Path.Lenght that will
                 *      // yield the same thing, because of the EndOfPathInstruction.Loop
                 *      // some weird shit, but it is what it is, i could implement an overload to pass a .stop
                 *      // but maybe other day
                 *      AddAnchor(path.length-0.01f, anchorSpacing, anchorOffset);
                 * }	*/

                SetHingesJoints();
            }
        }
Exemplo n.º 6
0
        private void Update_Internal(float delta)
        {
            if (!stopped)
            {
                if (pathCreator != null)
                {
                    path = pathCreator.path;
                }

                if (path == null)
                {
                    return;
                }

                distanceTravelled += speed * delta;
                transform.position = path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
                if (updateRotation)
                {
                    if (useDirectionToRotate)
                    {
                        var rot = path
                                  .GetDirectionAtDistance(distanceTravelled, endOfPathInstruction).LookRotation();
                        rot.Set(x: 0, z: 0);
                        transform.rotation = rot;
                    }
                    else
                    {
                        transform.rotation = path.GetRotationAtDistance(distanceTravelled, endOfPathInstruction);
                    }
                }
            }
        }
Exemplo n.º 7
0
    private void OnValidate()
    {
        if (obstacles == null)
        {
            obstacles = new List <GameObject>();
        }
        if (pathCreator == null)
        {
            pathCreator = GetComponent <PathCreator>();
        }
        if (prefab != null)
        {
            ClearObstacles();
            if (container == null)
            {
                container = transform;
            }
            VertexPath path = pathCreator.path;

            if (distance >= 0.5f)
            {
                for (float i = 0f; i < path.length; i += distance)
                {
                    obstacles.Add(Instantiate(prefab, path.GetPointAtDistance(i), rotate ? path.GetRotationAtDistance(i) : Quaternion.identity, container));
                }
            }
        }
    }
Exemplo n.º 8
0
    public static void GetPath(List <Vector3> points, bool isClosed, PathSpace space,
                               ref List <Vector3> results, float step)
    {
        results.Clear();

        if (points.Count < 2)
        {
            Debug.LogError("Path requires at least 2 anchor points.");
            return;
        }


        var bezierPath = new BezierPath(points, isClosed, space);

        var vertexPath = new VertexPath(bezierPath, 0.3f, 0.01f);

        float length   = vertexPath.length;
        float distance = 0;

        while (distance <= length)
        {
            Vector3 pos = vertexPath.GetPointAtDistance(distance, EndOfPathInstruction.Stop);

            results.Add(pos);
            distance += step;
        }
    }
Exemplo n.º 9
0
    public void AddObstacle(int index)
    {
        if (NextDistance > path.length)
        {
            ++cont;
            NextDistance = NextDistance % path.length;
        }
        if (NextDistance > middle_point)
        {
            half = 1;
        }
        else
        {
            half = 0;
        }

        string name = "Obstacles" + cont + half;

        GetParentObject(name);
        Vector3    position = path.GetPointAtDistance(NextDistance, endOfPathInstruction);
        Vector3    upward   = path.GetDirectionAtDistance(NextDistance, endOfPathInstruction);
        Vector3    forward  = path.GetNormalAtDistance(NextDistance, endOfPathInstruction);
        Quaternion rotation = Quaternion.LookRotation(forward, upward);

        Instantiate(obstacles[index], position, rotation, obstacles_object.transform);
        NextDistance += DistanceGap;
    }
Exemplo n.º 10
0
        //private void Update()
        //{
        //    counterColor += Time.deltaTime;

        //    if (counterColor > 20) counterColor = 0;

        //    startMat.color = Color.HSVToRGB(counterColor / 20, .33f, 1);
        //}

        public void Generate(float dst)
        {
            if (pathCreator != null && prefab != null && holder != null)
            {
                //DestroyObjects ();

                VertexPath path = pathCreator.path;

                Vector3    point = path.GetPointAtDistance(dst);
                Quaternion rot   = path.GetRotationAtDistance(dst);

                index++;

                if (index >= Walls.Count)
                {
                    index = 0;
                }

                dir *= -1;

                Walls[index].GetChild(0).GetComponent <MeshRenderer>().material = startMat;
                Walls[index].position = point;
                Walls[index].rotation = rot;
                Walls[index].transform.GetChild(0).localPosition = new Vector3(-0.5f, 0.4f * dir, 0);
            }
        }
Exemplo n.º 11
0
        void Generate()
        {
            if (pathCreator != null && prefab != null && holder != null)
            {
                DestroyObjects();

                VertexPath path = pathCreator.path;

                spacing = Mathf.Max(minSpacing, spacing);
                float dst = 0;

                while (dst < path.length)
                {
                    Vector3    point = path.GetPointAtDistance(dst);
                    Quaternion rot   = path.GetRotationAtDistance(dst);
                    if (count % 2 == 0)
                    {
                        Instantiate(prefab[0], point, rot, holder.transform);
                    }
                    else
                    {
                        Instantiate(prefab[1], point, rot, holder.transform);
                    }
                    dst += spacing;
                    count++;
                }
            }
        }
Exemplo n.º 12
0
 void Update()
 {
     if (path != null)
     {
         dstTravelled      += speed * Time.deltaTime;
         transform.position = path.GetPointAtDistance(dstTravelled);
     }
 }
Exemplo n.º 13
0
    //create the random pattern
    private void InstantiateTheRandom(GameObject prefab, GameObject holder)
    {
        Vector3    point = _path.GetPointAtDistance(_dst);
        Quaternion rot   = _path.GetRotationAtDistance(_dst);

        Instantiate(prefab, point + Vector3.up, rot, holder.transform);
        _dst += varStorge.spacingBtwObsticale;
    }
Exemplo n.º 14
0
    public override void OnUpdate(float deltaTime)
    {
        base.OnUpdate(deltaTime);

        if (!isActive)
        {
            return;
        }
        if (enemyState == EnemyState.die)
        {
            return;
        }
        CheckDirFollowPlayer(myPath.GetPointAtDistance(myPath.length, EndOfPathInstruction.Stop).x);
        distanceTravelled += speed * deltaTime;
        transform.position = myPath.GetPointAtDistance(distanceTravelled, EndOfPathInstruction.Stop);
        if (transform.position == myPath.GetPointAtDistance(myPath.length, EndOfPathInstruction.Stop))
        {
            gameObject.SetActive(false);
        }
    }
Exemplo n.º 15
0
    private void generateCheckpoints()
    {
        GameObject  startpoint = Resources.Load <GameObject>("Startpoint");
        GameObject  checkpoint = Resources.Load <GameObject>("Checkpoint");
        PathCreator pc         = GetComponent <PathCreator>();

        if (checkpointHolder == null)
        {
            GameObject obj = new GameObject();
            obj.name         = "Checkpoints";
            checkpointHolder = obj;
        }

        VertexPath path = pc.path;

        numCheckpoints = Mathf.Clamp((int)path.length / 10, 4, 10);
        float spacing = path.length / numCheckpoints;
        float dst     = 0;


        dst += spacing;

        while (dst < path.length)
        {
            Vector3    point = path.GetPointAtDistance(dst);
            Quaternion rot   = path.GetRotationAtDistance(dst) * Quaternion.Euler(90, 0, 90);
            Instantiate(checkpoint, point, rot, checkpointHolder.transform);
            dst += spacing;
        }

        // Startpoint:
        // Add the startpoint last since its the last checkpoint technically
        Vector3    point_start = path.GetPointAtDistance(0);
        Quaternion rot_start   = path.GetRotationAtDistance(0) * Quaternion.Euler(90, 0, 90);

        Instantiate(startpoint, point_start, rot_start, checkpointHolder.transform);
    }
Exemplo n.º 16
0
    public bool AnimatePath()
    {
        //if (!obj)
        //return;

        t           += Time.deltaTime * speed;
        obj.position = path.GetPointAtDistance(t, EndOfPathInstruction.Stop);
        obj.rotation = path.GetRotationAtDistance(t, EndOfPathInstruction.Stop);

        if (path.length > t)
        {
            return(false);
        }
        return(true);
    }
Exemplo n.º 17
0
 void Update()
 {
     if (currentPath != null)
     {
         CheckFront();
         dstTravelled      += CalculateSpeed() * Time.deltaTime;
         transform.position = currentPath.GetPointAtDistance(dstTravelled, EndOfPathInstruction.Stop);
         Quaternion newRot = currentPath.GetRotationAtDistance(dstTravelled, EndOfPathInstruction.Stop);
         transform.eulerAngles = new Vector3(0, newRot.eulerAngles.y - 180, 0);
         if (Vector3.Distance(transform.position, currentPath.GetPoint(.9999f)) <= .05f)
         {
             UpdateRoadAndPath();
         }
     }
 }
Exemplo n.º 18
0
    //Update is called once per frame
    void Update()
    {
        var vehilcesToTransfer = new Dictionary <Vehicle, Node>();
        var vehiclesToRemove   = new List <Vehicle>();

        foreach (var vehicle in vehicles)
        {
            var info = CreateRoadInfoForVehicle(vehicle);
            vehicle.UpdatePosition(info);

            if (vehicle.distanceOnCurrentRoadSegment > consequent.Find(c => c.node == vehicle.intermediateTarget.Current).path.length)
            {
                if (vehicle.intermediateTarget.Current.consequent.Count == 0 || vehicle.IsRouteFinished())
                {
                    SimulationManager.SpawnManager.NotifyVehicleRouteFinished(vehicle);
                    vehiclesToRemove.Add(vehicle);
                }
                else
                {
                    var nextHop = vehicle.GetNextTargetNode();
                    vehilcesToTransfer.Add(vehicle, vehicle.intermediateTarget.Current);
                    vehicle.MoveOnPath();
                    vehicle.distanceOnCurrentRoadSegment = 0;
                }
            }
            else
            {
                VertexPath path = consequent.Find(c => c.node == vehicle.intermediateTarget.Current).path;
                vehicle.transform.position = path.GetPointAtDistance(vehicle.distanceOnCurrentRoadSegment, EndOfPathInstruction.Stop) + new Vector3(0, 0, -3);
                vehicle.transform.rotation = path.GetRotationAtDistance(vehicle.distanceOnCurrentRoadSegment, EndOfPathInstruction.Stop);
            }
        }

        foreach (var pair in vehilcesToTransfer)
        {
            vehicles.Remove(pair.Key);
            pair.Value.vehicles.Add(pair.Key);
        }

        foreach (var item in vehiclesToRemove)
        {
            vehicles.Remove(item);
            SimulationManager.VehicleManager.Delete(item);
        }
    }
Exemplo n.º 19
0
    IEnumerator Following(VertexPath path)
    {
        Vector3 lastPoint = path.GetPointAtTime(1f, EndOfPathInstruction.Stop);
        float   befDist   = 0.5f;

        if (stopped == false)
        {
            while (DistanceXZ(transform.position, lastPoint) > 0.5f)
            {
                float distance = Vector3.Distance(this.transform.position, lastPoint);

                if (distance < stopDistance)
                {
                    stopped       = true;
                    body.velocity = Vector3.zero;
                }

                body.velocity = Vector3.ClampMagnitude(body.velocity, maxSpeed);
                body.AddForce(transform.forward * followSpeed, ForceMode.VelocityChange);
                float dist = path.GetClosestDistanceAlongPath(transform.position);
                if (dist < befDist)
                {
                    dist = befDist;
                }
                else
                {
                    befDist = dist;
                }

                Vector3 nextPoint = path.GetPointAtDistance(dist + followSpeed, EndOfPathInstruction.Stop);
                Vector3 diff      = nextPoint - transform.position;
                diff.y = 0;
                diff.Normalize();
                Debug.DrawLine(transform.position, nextPoint, Color.red);
                Debug.DrawRay(transform.position, diff, Color.gray);
                float angle = Mathf.Atan2(diff.x, diff.z) * Mathf.Rad2Deg;
                transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.up), rotateSpeed * Time.fixedDeltaTime);
                yield
                return(new WaitForFixedUpdate());
            }
            body.velocity = Vector3.zero;
        }
    }
Exemplo n.º 20
0
        private INode[] GenerateNodes()
        {
            VertexPath   path     = Road.path;
            List <INode> allNodes = new List <INode>();

            nodeSpacing = Mathf.Max(NODE_MIN_SPACING, nodeSpacing);
            float distance       = 0;
            int   nodesPerAnchor = 3;

            // Create all nodes
            while (distance < path.length)
            {
                Vector3 centre  = path.GetPointAtDistance(distance, TrackType);
                Vector3 normal  = path.GetNormalAtDistance(distance, TrackType);
                Vector3 forward = Road.path.GetDirectionAtDistance(distance, TrackType);

                distance += nodeSpacing;

                allNodes.Add(new Node(centre + normal * (RoadWidth - nodesRoadEdgeOffset) * -1, forward, allNodes.Count));
                allNodes.Add(new Node(centre, forward, allNodes.Count));
                allNodes.Add(new Node(centre + normal * (RoadWidth - nodesRoadEdgeOffset), forward, allNodes.Count));

                if (distance > path.length - nodeSpacing)
                {
                    break;
                }
            }

            // Fill node connections
            for (int i = 0; i < allNodes.Count; i++)
            {
                allNodes[i].Connections = new int[nodesPerAnchor];
                int neighbourIndexOffset = nodesPerAnchor - i % nodesPerAnchor;

                for (int j = 0; j < nodesPerAnchor; j++)
                {
                    int connectionIndex = (i + j + neighbourIndexOffset) % allNodes.Count;
                    allNodes[i].Connections[j] = allNodes[connectionIndex].ID;
                }
            }

            return(allNodes.ToArray());
        }
Exemplo n.º 21
0
    private void FixedUpdate()
    {
        for (int i = 0; i < AICars.Length; i++)
        {
            Vector3 nextPoint   = path.GetPointAtDistance(path.GetClosestDistanceAlongPath(AICars[i].transform.position) + AICars[i].AIDistanceFactor);
            float   signedAngle = Vector2.SignedAngle(AICars[i].transform.up, nextPoint - AICars[i].transform.position);
            bool    invert      = false;

            if (Mathf.Abs(signedAngle) < 107)
            {
                AICars[i].Forward();
            }
            else
            {
                AICars[i].Backward();
                invert = true;
            }

            if (signedAngle > 5)
            {
                if (!invert)
                {
                    AICars[i].Left();
                }
                else
                {
                    AICars[i].Right();
                }
            }
            else if (signedAngle < -5)
            {
                if (!invert)
                {
                    AICars[i].Right();
                }
                else
                {
                    AICars[i].Left();
                }
            }
        }
    }
Exemplo n.º 22
0
        void Generate()
        {
            if (pathCreator != null && prefab != null && holder != null)
            {
                DestroyObjects();

                VertexPath VertexPath = pathCreator.VertexPath;

                spacing = Mathf.Max(minSpacing, spacing);
                float dst = 0;

                while (dst < VertexPath.length)
                {
                    Vector3    point = VertexPath.GetPointAtDistance(dst);
                    Quaternion rot   = VertexPath.GetRotationAtDistance(dst);
                    Instantiate(prefab, point, rot, holder.transform);
                    dst += spacing;
                }
            }
        }
Exemplo n.º 23
0
    public void GenerateTube(bool file)
    {
        string name = "Tube";
        var    generated_tranform = transform.Find(name);

        if (generated_tranform != null)
        {
            DestroyImmediate(generated_tranform.gameObject);
            Debug.Log("destroyed");
        }
        tube = Create(name, gameObject);
        Debug.Log("create tube");

        PathCreator path_creator = gameObject.GetComponent <PathCreator>();

        if (path_creator != null)
        {
            VertexPath path = path_creator.path;

            /*if (file)
             * {
             *  BezierPath bp = path_creator.LoadPath();
             *  path = new VertexPath(bp, transform);
             * }
             * else
             * {
             *  path = path_creator.path;
             * }*/

            Debug.Log("got path");
            for (float distance = 0; distance < path.length; distance += 0.2f)
            {
                Vector3    position = path.GetPointAtDistance(distance, endOfPathInstruction);
                Vector3    upward   = path.GetDirectionAtDistance(distance, endOfPathInstruction);
                Vector3    forward  = path.GetNormalAtDistance(distance, endOfPathInstruction);
                Quaternion rotation = Quaternion.LookRotation(forward, upward);
                Instantiate(segment, position, rotation, tube.transform);
            }
        }
    }
Exemplo n.º 24
0
    // Start is called before the first frame update
    void Start()
    {
        // randomly pick a color and get the trail/ball combination for the color
        if (survival)
        {
            random = Random.Range(0, Min(balls.Length, trails.Length));
        }
        else
        {
            random = Random.Range(1, Min(balls.Length, trails.Length));
        }
        trail = trails[random];
        ball  = balls[random];

        Vector3[] points = { start, middle, end };
        path      = new VertexPath(new BezierPath(points), transform);
        trail     = Instantiate(trail, path.GetPointAtDistance(0), path.GetRotationAtDistance(0));
        startHole = Instantiate(holePrefabStart, start, startRotation);
        endHole   = Instantiate(holePrefabEnd, end, endRotation);
        travelDst = 0;
        spawned   = false;
    }
Exemplo n.º 25
0
    private void SetPositionOnDistance()
    {
        float mag = Joystick.GetMagnitude() / InputSensitivity;


        Quaternion rot = Track.GetRotationAtDistance(Dist);

        Player.rotation    = Quaternion.Euler(rot.eulerAngles.x, rot.eulerAngles.y, 0f);
        transform.rotation = Quaternion.Lerp(transform.rotation, Track.GetRotationAtDistance(Dist), CameraRotationSmoothing * Time.deltaTime);
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, 0f);

        Move = Track.GetPointAtDistance(Dist) + Vector3.up / 10f;
        transform.position = Move;

        Move = PlayerPos + Vector3.right * mag;
        Player.localPosition = Vector3.MoveTowards(Player.localPosition, Move, SideSpeed * Time.deltaTime);
        Player.localPosition = Vector3.ClampMagnitude(Player.localPosition, 3.5f);


        Car.position = Vector3.MoveTowards(Car.position, Player.position, Time.deltaTime * Speed);
        Car.LookAt(Player.position);
    }
Exemplo n.º 26
0
        void Generate()
        {
            if (pathCreator != null && holder != null)//(pathCreator != null && prefab != null && holder != null)
            {
                DestroyObjects();

                VertexPath path = pathCreator.path;

                spacing = Mathf.Max(minSpacing, spacing);
                float dst = 0;

                while (dst < path.length)
                {
                    if (dst == 0 || dst < initialstartspawn)
                    {
                        dst += spacing;
                        //in starting add diamond collection for more interactive
                    }
                    else
                    {
                        if (dst < path.length - 75)
                        {
                            Vector3    point = path.GetPointAtDistance(dst);
                            Quaternion rot   = path.GetRotationAtDistance(dst);
                            Instantiate(prefab[Random.Range(0, randommax)], point, rot, holder.transform);
                        }

                        dst += spacing;
                        //  Debug.Log(path.GetPointAtDistance(dst));
                    }

                    /* Vector3 point = path.GetPointAtDistance (dst);
                     * Quaternion rot = path.GetRotationAtDistance (dst);
                     * Instantiate (prefab[Random.Range(0,7)], point, rot, holder.transform);
                     * dst += spacing;*/
                }
            }
        }
Exemplo n.º 27
0
    private void Init(VertexPath path, int density)
    {
        float length = path.length;

        float distInterval = length / density;

        for (int i = 0; i < density; i++)
        {
            int   rand = Random.Range(0, 2);
            float dir  = LevelGenerator.instance.RoadWidth / 2.5f;
            if (rand == 1)
            {
                dir = -dir;
            }

            Vector3    offset = new Vector3(dir, 0.2f, 0f);
            Vector3    pos    = path.GetPointAtDistance(distInterval * i) + offset;
            Quaternion rot    = path.GetRotationAtDistance(distInterval * i);
            GameObject go     = Instantiate(CarPrefab, pos, Quaternion.Euler(rot.eulerAngles.x, rot.eulerAngles.y, 0f));
            go.AddComponent <EntityMover>().Init(path, distInterval * i, offset, Mathf.Sign(dir), Random.Range(20f, 30f), Random.Range(2f, 6f));
            go.AddComponent <HitTrigger>();
        }
    }
Exemplo n.º 28
0
    //public override void CollectObservations(VectorSensor sensor)
    //{
    //    // # Basic information
    //    Rigidbody rBody = GetComponent<Rigidbody>();
    //    // Agent positions & velocity
    //    sensor.AddObservation(this.transform.localPosition);
    //    sensor.AddObservation(rBody.velocity);
    //    // # Collect Path's observations
    //    float centerDistance = vertexPath.GetClosestDistanceAlongPath(this.transform.localPosition);
    //    for (int d = tickerStart; d <= tickerEnd; d++)
    //    {
    //        float distance = centerDistance + d * tickerSpace;
    //        Vector3 point = vertexPath.GetPointAtDistance(distance, EndOfPathInstruction.Loop);
    //        Vector3 normal = vertexPath.GetNormalAtDistance(distance, EndOfPathInstruction.Loop);

    //        AddObservationInXYZMode(sensor, point);
    //        AddObservationInXYZMode(sensor, normal);
    //    }
    //    // # Padding observations
    //    // If custom setting will have too more observations and cause the buffer overflow, We
    //    // must warn user (in Pyhon interface level).
    //    // Here we are padding the observation buffer with all zero
    //    int MaxObservationSize = GetComponent<BehaviorParameters>().BrainParameters.VectorObservationSize;
    //    for (int i = 0; i < MaxObservationSize - ObservationSize; i++)
    //        sensor.AddObservation(0);
    //}
    public override void CollectObservations(VectorSensor sensor)
    {
        // # Basic information
        Rigidbody rBody = GetComponent <Rigidbody>();

        // Agent velocity
        sensor.AddObservation(this.transform.localPosition);
        sensor.AddObservation(rBody.velocity);
        // # Collect Path's basic information
        float   centerDistance = vertexPath.GetClosestDistanceAlongPath(this.transform.localPosition);
        Vector3 direction      = vertexPath.GetDirectionAtDistance(centerDistance);
        // Check clockwise direction & determine ticker's start and end
        bool clockwise = (Vector3.Dot(rBody.velocity, direction) >= 0);
        int  t_s       = clockwise ? tickerStart : -tickerEnd;
        int  t_e       = clockwise ? tickerEnd : -tickerStart;

        // # Collect Path's observations
        for (int d = t_s; d <= t_e; d++)
        {
            float   distance = centerDistance + d * tickerSpace;
            Vector3 point    = vertexPath.GetPointAtDistance(distance, EndOfPathInstruction.Loop);
            Vector3 normal   = vertexPath.GetNormalAtDistance(distance, EndOfPathInstruction.Loop);
            AddObservationInXYZMode(sensor, point - this.transform.localPosition);
            AddObservationInXYZMode(sensor, normal);
        }
        // # Padding observations
        // If custom setting will have too more observations and cause the buffer overflow, We
        // must warn user (in Pyhon interface level).
        // Here we are padding the observation buffer with all zero
        int MaxObservationSize = GetComponent <BehaviorParameters>().BrainParameters.VectorObservationSize;

        for (int i = 0; i < MaxObservationSize - ObservationSize; i++)
        {
            sensor.AddObservation(0);
        }
    }
Exemplo n.º 29
0
    // Update is called once per frame
    void Update()
    {
        // if the ball or the trail hits the end point, destory them
        if (trail != null && trail.transform.position == path.GetPointAtTime(1, EndOfPathInstruction.Stop))
        {
            Destroy(trail, 3);
        }
        if (ball == null || ball.transform.position == path.GetPointAtTime(1, EndOfPathInstruction.Stop))
        {
            if (ball != null && survival)
            {
                if (ball.tag != "Bomb" && scorekeeper.caught)
                {
                    scorekeeper.caught = false;
                }
                else
                {
                    scorekeeper.lives--;
                }
            }
            // the ball can be null if it is caught and destoryed
            if (ball != null)
            {
                Destroy(ball);
            }
            Destroy(startHole);
            Destroy(endHole);
            Destroy(this.gameObject);
        }

        travelDst += Time.deltaTime * speed;
        if (trail != null)
        {
            trail.transform.position = path.GetPointAtDistance(travelDst, EndOfPathInstruction.Stop);
        }
        float prevDelay = delay;

        delay -= Time.deltaTime;
        if (delay < 0)
        {
            // if this is the first time delay became less than 0, then instantiate the ball
            if (prevDelay >= 0)
            {
                ball    = Instantiate(ball, path.GetPointAtDistance(0), path.GetRotationAtDistance(0));
                spawned = true;
                // mark end of path since ball.transform.position is not accurate
                ball.GetComponent <Explosion>().end = this.end;
                if (random == 0)
                {
                    Instantiate(GameObject.Find("AudioManager").GetComponent <AudioManager>().bombSpawn,
                                start, Quaternion.identity);
                }
                else
                {
                    Instantiate(GameObject.Find("AudioManager").GetComponent <AudioManager>().spawn,
                                start, Quaternion.identity);
                }
            }
            if (ball != null)
            {
                ball.transform.position = path.GetPointAtDistance(-delay * speed, EndOfPathInstruction.Stop);
                ball.transform.rotation = path.GetRotationAtDistance(-delay * speed, EndOfPathInstruction.Stop);
            }
        }
    }
Exemplo n.º 30
0
    public override void OnStateExcute(float deltaTime)
    {
        base.OnStateExcute(deltaTime);

        if (action.paths.Count > 0)
        {
            if (mTargetPoint == null)
            {
                mTargetPoint = action.paths.First.Value;
                mDistance    = 0;

                if (Chess.Instance.grid == BattleGrid.Rect)
                {
                    var tile = BattleRectGrid.Instance.TileAt(mTargetPoint.destination);
                    if (tile == null || tile.isValid == false)
                    {
                        action.Done();

                        var point = action.paths.First;
                        while (point != null)
                        {
                            point.Value.Failed(agent);
                            ObjectPool.ReturnInstance(point.Value);
                            point = point.Next;
                        }
                        action.paths.Clear();
                        mTargetPoint = null;
                    }
                }
                else
                {
                    var tile = BattleHexGrid.Instance.TileAt(mTargetPoint.destination);
                    if (tile == null || tile.isValid == false)
                    {
                        action.Done();
                        var point = action.paths.First;
                        while (point != null)
                        {
                            point.Value.Failed(agent);
                            ObjectPool.ReturnInstance(point.Value);
                            point = point.Next;
                        }
                        action.paths.Clear();
                        mTargetPoint = null;
                    }
                }
                if (mTargetPoint != null)
                {
                    //水平移动需要多久
                    float duration = Vector3.Distance(agent.position, mTargetPoint.destination) / SPEED;
                    if (duration > 0)
                    {
                        float halfTime = duration * 0.5f;
                        float height   = Math.Abs(GRAVITY) * halfTime * halfTime / 2;
                        //限制垂直高度
                        height = Mathf.Clamp(height, MINHEIGHT, MAXHEIGHT);

                        Vector3 center = (agent.position + mTargetPoint.destination) / 2f;
                        center.y = height;

                        List <Vector3> points = new List <Vector3>();
                        points.Add(agent.position);
                        points.Add(center);
                        points.Add(mTargetPoint.destination);

                        mBezierPath = new BezierPath(points, false, PathSpace.xyz);
                        mVertexPath = new VertexPath(mBezierPath, 0.3f, 0.01f);
                    }
                    else
                    {
                        mTargetPoint.Arrive(agent);
                        ObjectPool.ReturnInstance(mTargetPoint);
                        mTargetPoint = null;
                        action.paths.RemoveFirst();
                    }
                }
            }

            if (mTargetPoint != null)
            {
                Vector3 direction = mTargetPoint.destination - agent.position;

                agent.position = mVertexPath.GetPointAtDistance(mDistance, EndOfPathInstruction.Stop);

                direction.y = 0;
                if (direction != Vector3.zero)
                {
                    agent.rotation = Quaternion.LookRotation(direction);
                }

                mDistance += SPEED * deltaTime;
                if (mDistance > mVertexPath.length)
                {
                    agent.position = mTargetPoint.destination;

                    mDistance = 0;
                    mTargetPoint.Arrive(agent);
                    ObjectPool.ReturnInstance(mTargetPoint);

                    mTargetPoint = null;
                    action.paths.RemoveFirst();
                }
            }
        }
        else
        {
            action.Done();
        }
    }