Beispiel #1
0
    } //centerLine of PlayerCar in PCH

    public void DrawCenterLine(GameObject car, float carTf, CurvySpline curvySpline, Texture2D lineRendererTxt)
    {
        Vector3 heading        = curvySpline.Interpolate(0) - car.transform.position;
        float   increaseAmount = 1f / (curvySpline.Length * SPLINE_GIZMO_SMOOTHNESS);

        if (Vector3.Dot(heading, car.transform.forward) > 0) //starting point is in front of me
        {
            for (float i = carTf; i > 0; i -= increaseAmount)
            {
                Vector3 pos = curvySpline.Interpolate(i);
                CenterPoints.Add(pos);
            }
        }
        else //starting point is behind me
        {
            for (float i = carTf; i < 1; i += increaseAmount)
            {
                Vector3 pos = curvySpline.Interpolate(i);
                CenterPoints.Add(pos);
            }
        }

        lineRenderer2.positionCount = CenterPoints.Count;
        lineRenderer2.SetPositions(CenterPoints.ToArray());
        lineRenderer2.colorGradient = MakeLineRendererGradient(centerLineColor);
        lineRenderer2.material.SetColor("_Color", CenterLineColor); //set tint color of lineRenderer
        Texture2D txt = UpdateParams(centerLineColor, lineRendererTxt);

        lineRenderer2.material.SetTexture("_MainTex", txt);
        CenterPoints.Clear();
    } //centerLine of PlayerCar in SF
Beispiel #2
0
 void InitPosAndRot()
 {
     if (!Spline)
     {
         return;
     }
     if (Spline.Interpolate(InitialF) != mTransform.position)
     {
         mTransform.position = Spline.Interpolate(InitialF);
     }
     // Rotate the transform to match the spline's orientation?
     if (SetOrientation && mTransform.rotation != Spline.GetOrientationFast(InitialF))
     {
         mTransform.rotation = Spline.GetOrientationFast(InitialF);
     }
 }
Beispiel #3
0
        void DoInterpolate()
        {
            if (!mSpline.IsInitialized)
            {
                return;
            }
            GameObject go = Fsm.GetOwnerDefaultTarget(GameObject);

            if (go)
            {
                float   tf = (PositionMode == CurvyPositionMode.Relative) ? CurvyUtility.ClampTF(Position.Value, Clamping) : mSpline.DistanceToTF(Position.Value, Clamping);
                Vector3 p  = (UseCache.Value) ? mSpline.InterpolateFast(tf) : mSpline.Interpolate(tf);

                if (Space == Space.Self)
                {
                    go.transform.localPosition = p;

                    if (SetOrientation)
                    {
                        go.transform.localRotation = mSpline.GetOrientationFast(tf);
                    }
                }
                else
                {
                    go.transform.position = mSpline.transform.TransformPoint(p);

                    if (SetOrientation)
                    {
                        go.transform.rotation = mSpline.transform.rotation * mSpline.GetOrientationFast(tf);
                    }
                }
            }
        }
Beispiel #4
0
        // Use this for initialization
        IEnumerator Start()
        {
            if (Spline && Cube)
            {
                while (!Spline.IsInitialized)
                {
                    yield return(null);
                }

                cubes    = new Transform[Amount];
                tf       = new float[Amount];
                dir      = new int[Amount];
                cubes[0] = Cube;
                tf[0]    = 0;
                dir[0]   = (Speed >= 0) ? 1 : -1;
                // Scale Cube depending on Spline length and number of cubes
                float sc = Spline.Length / Amount;
                Cube.localScale = new Vector3(sc * 0.7f, sc * 0.7f, sc * 0.7f);

                // Create and position cubes
                Cube.position = Spline.InterpolateByDistance(0);
                for (int i = 1; i < Amount; i++)
                {
                    {
                        tf[i]             = Spline.DistanceToTF(i * sc);
                        cubes[i]          = getCube();
                        cubes[i].position = Spline.Interpolate(tf[i]);
                        cubes[i].rotation = Spline.GetOrientationFast(tf[i]);
                        dir[i]            = (Speed >= 0) ? 1 : -1;
                    }
                }

                Speed = Mathf.Abs(Speed);
            }
        }
Beispiel #5
0
    public void UpdateATL(CurvySpline spline)
    {
        t = spline.GetNearestPointTF(transform.position);
        Vector3 splineAtT = spline.Interpolate(t);

        if (transform.position.y < splineAtT.y)
        {
            lastPos = splineAtT;
            Camera.main.GetComponent <CameraController_three> ().falling = true;
            //SceneManager.LoadScene ("three");
            StartCoroutine(Fall(5.0f, spline));                 //pass in length of fall
        }
        else
        {
            Camera.main.GetComponent <CameraController_three> ().falling = false;
        }

        if (!m_Jump)
        {
            m_Jump = Input.GetButtonDown("Jump");
        }

        //disabling jump
        m_Jump = false;
    }
Beispiel #6
0
    /// <summary>
    /// Gets the interpolated position for a certain group TF
    /// </summary>
    /// <remarks>TF (Total Fragment) relates to the total length of the group</remarks>
    /// <param name="tf">TF value identifying position in the group (0..1)</param>
    /// <returns>the interpolated position</returns>
    public override Vector3 Interpolate(float tf)
    {
        float       localTF;
        CurvySpline spl = TFToSpline(tf, out localTF);

        return(spl.Interpolate(localTF));
    }
        void FixedUpdate()
        {
            if (Spline)
            {
                var v = Input.GetAxis("Vertical") * VSpeed;
                var h = Input.GetAxis("Horizontal") * HSpeed;

                Vector3 p;
                // get nearest TF and point on spline
                mTF = Spline.GetNearestPointTF(transform.localPosition, out p);
                // apply forward thrust along spline direction (tangent)
                if (v != 0)
                {
                    mRigidBody.AddForce(Spline.GetTangentFast(mTF) * v, ForceMode.Force);
                }
                // apply side thrust to left/right from the spline's "forward" vector
                if (h != 0)
                {
                    Vector3 offset = Spline.GetExtrusionPointFast(mTF, 1, 90);
                    Vector3 hdir   = p - offset;
                    mRigidBody.AddForce(hdir * h, ForceMode.Force);
                }
                if (Input.GetKeyDown(KeyCode.Space))
                {
                    mRigidBody.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
                }

                // continously drag toward the spline to add some magic gravity
                mRigidBody.AddForce((Spline.Interpolate(mTF) - transform.localPosition) * CenterDrag, ForceMode.VelocityChange);
            }
        }
Beispiel #8
0
    // Update is called once per frame
    public void UpdateATL(SplineLord_one splineLord_one, BookController bookController)
    {
        //print (Input.mouseScrollDelta.y);

        speed = -Input.mouseScrollDelta.y * _sensitivity;
        transform.position -= transform.up * _offset.y;
        _jumpTimer          = Mathf.Clamp01(_jumpTimer - Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space) && _jumpTimer <= 0.0f)           //getkeydown only true first frame down, getkeyup true first frame released, getkey is true if down and false if up
        {
            _jumpTimer = 1.0f;
        }
        _offset = new Vector3(0.0f, Mathf.Sin(AxKEasing.EaseOutQuad(0.0f, 1.0f, 1.0f - _jumpTimer) * Mathf.PI), 0.0f);

        CurvySpline curSpline = splineLord_one.GetSpline();

        //this way gets nearest point on spline to current position
        t  = curSpline.GetNearestPointTF(transform.position);
        t += (speed / curSpline.Length) * Time.deltaTime * 5.0f;
        transform.position = curSpline.Interpolate(t);

        //Vector3 sForward = curSpline.GetTangentToSpline( t );
        //Vector3 sNormal = curSpline.GetOrientationOnSpline (t);
        //Quaternion lookRotation = Quaternion.LookRotation (sForward, sNormal);

        transform.rotation = Quaternion.Slerp(transform.rotation, curSpline.GetOrientationFast(t), Time.deltaTime * 5.0f);

        transform.position += transform.up * _offset.y;         //places player over spline

        int     indexOffset = 4;
        Vector3 v1          = curSpline.ControlPoints [0 + indexOffset].transform.position - curSpline.ControlPoints [1 + indexOffset].transform.position;
        Vector3 v2          = transform.position - curSpline.ControlPoints [1 + indexOffset].transform.position;
        float   dot         = Vector3.Dot(v1, v2);

        //print ( (Time.timeSinceLevelLoad % 2.0f).ToString( "F7" ) + "  " + ( Time.timeSinceLevelLoad ).ToString( "F5" ) + "  " + ( Time.timeSinceLevelLoad / 2.0f ).ToString( "F6") );
        if (Time.timeSinceLevelLoad % 2.0f <= 0.1f)          // dot < -.2)
        {
            //splineLord.CreateControlPoint ();
        }

        if (t > .5)
        {
            //SplineLord.GenerateSpline(curSpline);
        }

        /*
         * if (t > .5)
         * {
         * splineLord.RegisterSpline() (next: get end pt from data stream)
         * delete last spline
         * }
         */
    }
    IEnumerator CameraFollowPathCoroutine(CurvySpline path, float duration, AnimationCurve cameraEvolutionOnPathCurve, Transform lookAtObjectStart, Transform lookAtObjectEnd, GameObject objectToDisplayText, string localisationKey, GameObject animationToPlay, string nameAnimationToPlay)
    {
        float elapsedTime = 0;

        if (textToErase != null && textToErase.GetComponent <CutScenesText3D>() != null)
        {
            textToErase.GetComponent <CutScenesText3D>().MessageToErase();
        }
        textToErase = objectToDisplayText;

        if (objectToDisplayText != null && objectToDisplayText.GetComponent <CutScenesText3D>() != null)
        {
            objectToDisplayText.GetComponent <CutScenesText3D>().MessageToDisplay(localisationKey);
        }

        if (animationToPlay != null && animationToPlay.GetComponent <Animation>())
        {
            animationToPlay.GetComponent <Animation>().Play(nameAnimationToPlay);
        }

        while (elapsedTime < duration)
        {
            float k         = elapsedTime / duration;
            float abstractK = Mathf.Clamp01(cameraEvolutionOnPathCurve.Evaluate(k));

            cutsceneCamera.transform.position = path.Interpolate(abstractK);
            cutsceneCamera.transform.LookAt(Vector3.Lerp(lookAtObjectStart.position, lookAtObjectEnd.position, abstractK));


            /*if (GameManager.instance.currentState != GameManager.STATE.PAUSE) {
             *  elapsedTime += Time.deltaTime;
             * }*
             */

            yield return(null);
        }

        cutsceneCamera.transform.position = path.Interpolate(1);
        cutsceneCamera.transform.LookAt(lookAtObjectEnd.position);
    }
Beispiel #10
0
    /// <summary>
    /// Builds a mesh from a spline (2D), taking interpolated points based on curvation angle
    /// </summary>
    /// <param name="spline">the spline to use</param>
    /// <param name="ignoreAxis">the axis to ignore (0=x,1=y,2=z)</param>
    /// <param name="close">True to create a mesh with triangles, False to create a vertex line mesh</param>
    /// <param name="angleDiff">the curvation angle used to interpolate points</param>
    public static Mesh CreateSplineMesh(CurvySpline spline, int ignoreAxis, bool close, float angleDiff)
    {
        float          tf    = 0;
        int            dir   = 1;
        List <Vector3> verts = new List <Vector3>();

        verts.Add(spline.Transform.worldToLocalMatrix.MultiplyPoint3x4(spline.Interpolate(0)));
        while (tf < 1)
        {
            verts.Add(spline.Transform.worldToLocalMatrix.MultiplyPoint3x4(spline.MoveByAngle(ref tf, ref dir, angleDiff, CurvyClamping.Clamp, 0.005f)));
        }

        return(buildSplineMesh(verts.ToArray(), ignoreAxis, !close));
    }
Beispiel #11
0
    void InitPosAndRot()
    {
        if (!Spline)
        {
            return;
        }
        float tf = Spline.DistanceToTF(InitialDistance);

        mTransform.position = Spline.Interpolate(tf);
        if (SetOrientation)
        {
            mTransform.rotation = Spline.GetOrientationFast(tf);
        }
    }
Beispiel #12
0
    } //NavigationLine of PlayerCar and TrafficCar in SF

    public void DrawCenterLine(float carTf, PlayerCarLines.Lane lane, CurvySpline curvySpline, Texture2D lineRendererTxt)
    {
        float increaseAmount = 1f / (curvySpline.Length * SPLINE_GIZMO_SMOOTHNESS);

        float endTf = carTf;

        if (lane.Equals(PlayerCarLines.Lane.RIGHT))
        {
            int direction = 1;
            curvySpline.MoveByLengthFast(ref endTf, ref direction, 75.0f, CurvyClamping.Clamp); //this is to determine a constant length of the curve drawn, since Tf isn't proportional to the curve length, so you can't use a constant value!
            for (float i = carTf; i < endTf; i += increaseAmount)
            {
                Vector3 pos = curvySpline.Interpolate(i);
                CenterPoints.Add(pos);
            }
        }
        else
        {
            int direction = -1;
            curvySpline.MoveByLengthFast(ref endTf, ref direction, 75.0f, CurvyClamping.Clamp); //this is to determine a constant length of the curve drawn, since Tf isn't proportional to the curve length, so you can't use a constant value!
            for (float i = carTf; i > endTf; i -= increaseAmount)
            {
                Vector3 pos = curvySpline.Interpolate(i);
                CenterPoints.Add(pos);
            }
        }

        lineRenderer2.positionCount = CenterPoints.Count;
        lineRenderer2.SetPositions(CenterPoints.ToArray());
        lineRenderer2.colorGradient = MakeLineRendererGradient(centerLineColor);
        lineRenderer2.material.SetColor("_Color", CenterLineColor); //set tint color of particle shader
        Texture2D txt = UpdateParams(centerLineColor, lineRendererTxt);

        lineRenderer2.material.SetTexture("_MainTex", txt);
        CenterPoints.Clear();
    } //centerLine of PlayerCar in PCH
Beispiel #13
0
//	public Object[] prefabs;
    public void CreateObstacle(CurvySpline curSpline)
    {
        GameObject newGameObject = GameObject.CreatePrimitive(PrimitiveType.Cube); //create GO, add mesh filter with cube mesh and adds mesh renderer

        newGameObject.transform.position = curSpline.Interpolate(0.3f);            // place obstacle ahead of player

        //Obstacle obstacle = newGameObject.AddComponent<JumpObstacle>();
        Obstacle obstacle = newGameObject.AddComponent <MiniGameObstacle>();

        obstacle.StartATL();

        RegisterObject(obstacle);

        print("cube");
    }
Beispiel #14
0
    IEnumerator LaneKeeping(float waitTime)
    {
        while (true)
        {
            yield return(new WaitForSeconds(waitTime));

            RaycastHit  hit;
            CurvySpline curvySpline             = null;
            CurvySpline pathEnhancedCurvySpline = null;
            if (Physics.Raycast(rayCastPos.position, rayCastPos.TransformDirection(-Vector3.up), out hit, 10.0f, 1 << LayerMask.NameToLayer("Graphics")))
            {
                curvySpline             = hit.collider.gameObject.GetComponent <CurvySpline>();
                pathEnhancedCurvySpline = pathEnhanced.GetComponent <CurvySpline>();
                if (curvySpline.IsInitialized && pathEnhancedCurvySpline.IsInitialized)
                {
                    //Debug.Log("meshcollider found is: " + hit.collider);
                    float   carTf           = curvySpline.GetNearestPointTF(transform.position); //determine the nearest t of the car with respect to the centerLine
                    Vector3 centerLinePoint = curvySpline.Interpolate(carTf);
                    float   dist            = Vector3.Distance(transform.position, centerLinePoint);
                    Lane    lane            = MonitorLane(centerLinePoint); //this is to understand if I am partially in the oncoming lane

                    if (dist < 2.0f && lane == Lane.RIGHT)                  //if dist2 < 2.7f I am in the right lane
                    {
                        linesUtilsAlt.CenterLineColor = linesUtilsAlt.ChangeMatByDistance(dist / 2.0f);
                        SetDashBoardColor(dist, 2.0f);
                    }

                    else if (dist >= 2.0f && lane == Lane.RIGHT)
                    {
                        linesUtilsAlt.CenterLineColor = new Color32(0x00, 0xFF, 0x00, 0x00);
                        laneState = LaneState.GREEN;
                    }

                    else if (lane == Lane.OPPOSITE) // this is to draw the redLine only when the PlayerCar is moving to the left, if it is moving to the right the line doesn't have to be red!
                    {
                        linesUtilsAlt.CenterLineColor = new Color32(0xFF, 0x00, 0x00, 0xFF);
                        laneState = LaneState.RED;
                    }

                    linesUtilsAlt.DrawCenterLine(gameObject, carTf, curvySpline, ResourceHandler.instance.sprites[36].texture);
                }
            }
            else
            {
                laneState = LaneState.GREEN;
            }
        }
    }
Beispiel #15
0
 // Update is called once per frame
 void Update()
 {
     if (Spline && Spline.IsInitialized && Lookup)
     {
         // convert Lookup position to Spline's local space
         var lookupPos = Spline.transform.InverseTransformPoint(Lookup.position);
         // get the nearest point's TF on spline
         Timer.Start();
         float nearestTF = Spline.GetNearestPointTF(lookupPos);
         Timer.Stop();
         // convert the spline pos back to world space and set
         transform.position  = Spline.transform.TransformPoint(Spline.Interpolate(nearestTF));
         StatisticsText.text =
             string.Format("Blue Curve Cache Points: {0} \nAverage Lookup (ms): {1:0.000}", Spline.CacheSize, Timer.AverageMS);
     }
 }
        void DoFindPoint()
        {
            if (!mSpline.IsInitialized || SourcePoint.IsNone)
            {
                return;
            }

            if (StoreTF.IsNone && StorePosition.IsNone && StoreUpVector.IsNone && StoreRotation.IsNone && StoreTangent.IsNone)
            {
                return;
            }

            Vector3 pos = (Space == Space.Self) ? SourcePoint.Value : mSpline.transform.InverseTransformPoint(SourcePoint.Value);

            float _tf = mSpline.GetNearestPointTF(pos);

            if (StoreTF.IsNone == false)
            {
                StoreTF.Value = _tf;
            }

            if (StorePosition.IsNone == false)
            {
                StorePosition.Value = (Space == Space.Self) ? mSpline.Interpolate(_tf) : mSpline.transform.TransformPoint(mSpline.Interpolate(_tf));
            }

            if (StoreTangent.IsNone == false)
            {
                StoreTangent.Value = (Space == Space.Self) ? mSpline.GetTangent(_tf) : mSpline.transform.TransformDirection(mSpline.GetTangent(_tf));
            }

            if (StoreUpVector.IsNone == false)
            {
                StoreUpVector.Value = (Space == Space.Self) ? mSpline.GetOrientationUpFast(_tf) : mSpline.transform.TransformDirection(mSpline.GetOrientationUpFast(_tf));
            }
            if (StoreRotation.IsNone == false)
            {
                if (Space == Space.Self)
                {
                    StoreRotation.Value = (StoreUpVector.IsNone) ? mSpline.GetOrientationFast(_tf) : Quaternion.LookRotation(mSpline.GetTangent(_tf), StoreUpVector.Value);
                }
                else
                {
                    StoreRotation.Value = Quaternion.LookRotation(mSpline.transform.TransformDirection(mSpline.GetTangent(_tf)), mSpline.transform.TransformDirection(mSpline.GetOrientationUpFast(_tf)));
                }
            }
        }
Beispiel #17
0
    public CurvyMeshSegmentInfo(SplinePathMeshBuilder mb, float tf, float distance, Vector3 scale)
    {
        Spline    = mb.Spline;
        TF        = tf;
        mDistance = distance;

        Vector3 p = (mb.FastInterpolation) ? Spline.InterpolateFast(TF) : Spline.Interpolate(TF);

        if (mb.UseWorldPosition)
        {
            Matrix = Matrix4x4.TRS(mb.Transform.InverseTransformPoint(p), Spline.GetOrientationFast(TF), scale);
        }
        else
        {
            Matrix = Matrix4x4.TRS(Spline.Transform.InverseTransformPoint(p), Spline.GetOrientationFast(TF), scale);
        }
    }
Beispiel #18
0
    void InitPosAndRot()
    {
        if (!Spline)
        {
            return;
        }
        // Get the TF for the current distance
        float tf = Spline.DistanceToTF(InitialDistance);

        // move Transform onto the spline
        mTransform.position = Spline.Interpolate(tf);
        // Rotate the transform to match the spline's orientation?
        if (SetOrientation)
        {
            mTransform.rotation = Spline.GetOrientationFast(tf);
        }
    }
Beispiel #19
0
    IEnumerator LaneKeeping(float waitTime)
    {
        while (true)
        {
            yield return(new WaitForSeconds(waitTime));

            RaycastHit  hit;
            CurvySpline curvySpline             = null;
            CurvySpline pathEnhancedCurvySpline = null;
            if (Physics.Raycast(rayCastPos.position, rayCastPos.TransformDirection(-Vector3.up), out hit, 10.0f, 1 << LayerMask.NameToLayer("Graphics")))
            {
                curvySpline             = hit.collider.gameObject.GetComponent <CurvySpline>();
                pathEnhancedCurvySpline = pathEnhanced.GetComponent <CurvySpline>();
                if (curvySpline.IsInitialized && pathEnhancedCurvySpline.IsInitialized)
                {
                    float carTf  = curvySpline.GetNearestPointTF(transform.position); //determine the nearest t of the car with respect to the centerLine
                    float carTf2 = pathEnhancedCurvySpline.GetNearestPointTF(transform.position);
                    float dist   = Vector3.Distance(transform.position, curvySpline.Interpolate(carTf));
                    Lane  lane   = MonitorLane(pathEnhancedCurvySpline.GetTangentFast(carTf2)); //this is to understand if I am partially in the oncoming lane
                    if (dist < 4.0f && lane == Lane.RIGHT)
                    {
                        linesUtilsAlt.CenterLineColor = linesUtilsAlt.ChangeMatByDistance(dist / 4.0f);
                        SetDashBoardColor(dist, 4.0f);
                    }

                    else if (dist >= 4.0f && lane == Lane.RIGHT)
                    {
                        linesUtilsAlt.CenterLineColor = new Color32(0x00, 0xFF, 0x00, 0x00);
                        laneState = LaneState.GREEN;
                    }

                    else if (lane == Lane.OPPOSITE)
                    {
                        linesUtilsAlt.CenterLineColor = new Color32(0xFF, 0x00, 0x00, 0xFF);
                        laneState = LaneState.RED;
                    }

                    linesUtilsAlt.DrawCenterLine(carTf, MonitorLane(curvySpline.GetTangentFast(carTf)), curvySpline, ResourceHandler.instance.sprites[33].texture);
                }
            }
            else
            {
                laneState = LaneState.GREEN;
            }
        }
    }
Beispiel #20
0
    public void DrawLine(GameObject car, CurvySpline curvySpline, float carTf)
    {
        float increaseAmount = 1f / (curvySpline.Length * SPLINE_GIZMO_SMOOTHNESS);
        int   direction      = 1;
        float endTf          = carTf;

        curvySpline.MoveByLengthFast(ref endTf, ref direction, 75.0f, CurvyClamping.Clamp); //this is to determine a constant length of the curve drawn, since Tf isn't proportional to the curve length, so you can't use a constant value!

        for (float i = carTf; i < endTf; i += increaseAmount)
        {
            Vector3 pos = curvySpline.Interpolate(i);
            LinePoints.Add(pos);
        }

        lineRenderer.positionCount = LinePoints.Count;
        lineRenderer.SetPositions(LinePoints.ToArray());
        LinePoints.Clear();
    } //NavigationLine of PlayerCar and TrafficCar in PCH
Beispiel #21
0
    public void UpdateATL(ThirdPersonUserControl player_three, Crosshair crosshair, CurvySpline spline)
    {
        _targetDelay -= Time.deltaTime;

        // aim through crosshair
        Quaternion targetDirection = Quaternion.LookRotation(crosshair.transform.forward);

        // passed the crosshair and delay
        if (_targetDelay < 0.5f)
        {
            if (_speed > 10.0f)
            {
                _speed -= Time.deltaTime;
            }

            if (Vector3.Distance(gameObject.transform.position, player_three.transform.position) < 5.0f)
            {
                onceAround = true;
            }

            // going around track
            if (!onceAround)
            {
                float t = spline.GetNearestPointTF(gameObject.transform.position);
                t *= .95f;
                Vector3 splineUp       = spline.GetRotatedUpFast(t, 0);
                Vector3 targetPosition = spline.Interpolate(t) + splineUp * 1.7f;

                targetDirection = Quaternion.LookRotation((targetPosition - transform.position).normalized);
            }
            // circling player - should be the gun
            else if (onceAround)
            {
                targetDirection = Quaternion.LookRotation(((player_three.transform.position + player_three.transform.up) - transform.position).normalized); //aim at heart
            }
        }

        transform.rotation = Quaternion.Slerp(transform.rotation, targetDirection, Time.deltaTime);
        Vector3 velocity = (transform.forward) * _speed;

        GetComponent <Rigidbody>().MovePosition(transform.position + velocity * Time.deltaTime);
    }
    void Set()
    {
        float tf;

        // First get the TF if needed
        if (UseWorldUnits)
        {
            if (Distance >= Spline.Length)
            {
                Distance -= Spline.Length;
            }
            else if (Distance < 0)
            {
                Distance += Spline.Length;
            }
            tf = Spline.DistanceToTF(Distance);
        }
        else
        {
            if (Distance >= 1)
            {
                Distance -= 1;
            }
            else if (Distance < 0)
            {
                Distance += 1;
            }
            tf = Distance;
        }

        // Set the position
        transform.position = Spline.Interpolate(tf);
        // Set the rotation
        if (SetOrientation)
        {
            transform.rotation = Spline.GetOrientationFast(tf);
        }
    }
Beispiel #23
0
    public void UpdateATL(ThirdPersonUserControl player, CurvySpline spline)
    {
        if (!init && spline.IsInitialized)
        {
            init = true;
        }

        if (!init)
        {
            return;
        }

        //print("mouse x " + Input.GetAxis("Mouse X") + ", mouse y " + Input.GetAxis("Mouse Y"));
        offset += new Vector3(-Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"), 0.0f);

        t = spline.GetNearestPointTF(player.transform.position);
        Vector3 splineUp = spline.GetRotatedUpFast(t, 0);
        //AxKDebugLines.AddLine (player.transform.position, player.transform.position + splineUp, Color.red, .001f);
        Vector3 splineForward = spline.GetTangent(t);
        Vector3 splineRight   = Vector3.Cross(splineUp, splineForward);

        Vector3 tempOffset = splineRight * offset.x + splineUp * offset.y;         //changed from Vector3.up

        float   targetPositionT = t - offsetCrosshair / spline.Length;
        Vector3 targetT         = spline.Interpolate(targetPositionT);
        Vector3 targetPosition  = targetT + tempOffset;

        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth * 3.0f);
        //transform.localRotation = Quaternion.Slerp( transform.localRotation, Quaternion.LookRotation (-splineForward.normalized), Time.deltaTime * smooth );

        //clamp the final position to this
        Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);

        pos.x = Mathf.Clamp01(pos.x);
        pos.y = Mathf.Clamp01(pos.y);
        transform.position = Camera.main.ViewportToWorldPoint(pos);

        //transform.position = targetPosition;
        transform.localRotation = Camera.main.transform.localRotation;

        if (fire)         //fire is only true for one frame
        {
            _small.gameObject.GetComponent <Renderer> ().material  = fireS;
            _medium.gameObject.GetComponent <Renderer> ().material = fireM;
            _large.gameObject.GetComponent <Renderer> ().material  = fireL;

            //print ("in fire, mat name = " + _medium.gameObject.GetComponent<Renderer> ().material.name);
            StartCoroutine(Delay(.5f));
        }
        else if (aim && !fire)
        {
            _small.localRotation  = Quaternion.Euler(transform.localRotation.y, transform.localRotation.x, tempOffset.x * 300.0f);
            _medium.localRotation = Quaternion.Euler(transform.localRotation.y, transform.localRotation.x, tempOffset.y * 300.0f);             //y = Time.time; // * 180.0f; // Quaternion.AngleAxis (Time.time * 180.0f , transform.forward);

            _small.gameObject.GetComponent <Renderer> ().material  = aimS;
            _medium.gameObject.GetComponent <Renderer> ().material = aimM;
            _large.gameObject.GetComponent <Renderer> ().material  = aimL;
            //print ("in aim, mat name = " + _medium.gameObject.GetComponent<Renderer> ().material.name);
        }
        else
        {
            //ease back. only call on return
            _small.localRotation  = Quaternion.Slerp(_small.localRotation, Quaternion.Euler(Vector3.zero), Time.deltaTime);
            _medium.localRotation = Quaternion.Slerp(_medium.localRotation, Quaternion.Euler(Vector3.zero), Time.deltaTime);

            _small.gameObject.GetComponent <Renderer> ().material  = readyS;
            _medium.gameObject.GetComponent <Renderer> ().material = readyM;
            _large.gameObject.GetComponent <Renderer> ().material  = readyL;
            //print ("in ready, mat name = " + _medium.gameObject.GetComponent<Renderer> ().material.name);
        }
    }
    void Calculate()
    {
        if (selcount == 0)
        {
            return;
        }
        pos = new UnityEngine.Vector3[selcount];
        up  = new UnityEngine.Vector3[selcount];
        tan = new UnityEngine.Vector3[selcount];

        for (int i = 0; i < selcount; i++)
        {
            pos[i] = (UseWorldUnits) ? Spline.InterpolateByDistance(StartOffset + Step * i) : Spline.Interpolate(StartOffset + Step * i);
            up[i]  = (UseWorldUnits) ? Spline.GetOrientationUpFast(Spline.DistanceToTF(StartOffset + Step * i)) : Spline.GetOrientationUpFast(StartOffset + Step * i);
            tan[i] = (UseWorldUnits) ? Spline.GetTangentByDistance(StartOffset + Step * i) : Spline.GetTangent(StartOffset + Step * i);
        }
    }
Beispiel #25
0
        protected CGData GetSplineData(CurvySpline spline, bool fullPath, CGDataRequestRasterization raster, CGDataRequestMetaCGOptions options)
        {
            if (spline == null || spline.Count == 0)
            {
                return(null);
            }
            List <ControlPointOption> optionsSegs = new List <ControlPointOption>();
            int   materialID = 0;
            float maxStep    = float.MaxValue;

            var data = (fullPath) ? new CGPath() : new CGShape();
            // calc start & end point (distance)
            float startDist;
            float endDist;

            getRange(spline, raster, out startDist, out endDist);

            float stepDist = (endDist - startDist) / (raster.Resolution - 1);

            data.Length = endDist - startDist;

            // initialize with start TF
            float tf      = spline.DistanceToTF(startDist);
            float startTF = tf;
            float endTF   = (endDist > spline.Length && spline.Closed) ? spline.DistanceToTF(endDist - spline.Length) + 1 : spline.DistanceToTF(endDist);

            // Set properties
            data.SourceIsManaged = IsManagedResource(spline);
            data.Closed          = spline.Closed;
            data.Seamless        = spline.Closed && raster.Length == 1;


            if (data.Length == 0)
            {
                return(data);
            }

            // Scan input spline and fetch a list of control points that provide special options (Hard Edge, MaterialID etc...)
            if (options)
            {
                optionsSegs = CGUtility.GetControlPointsWithOptions(options,
                                                                    spline,
                                                                    startDist,
                                                                    endDist,
                                                                    raster.Mode == CGDataRequestRasterization.ModeEnum.Optimized,
                                                                    out materialID,
                                                                    out maxStep);
            }

            // Setup vars
            List <SamplePointUData> extendedUVData = new List <SamplePointUData>();
            List <Vector3>          pos            = new List <Vector3>();
            List <float>            relF           = new List <float>();
            List <float>            sourceF        = new List <float>();
            List <Vector3>          tan            = new List <Vector3>();
            List <Vector3>          up             = new List <Vector3>();
            float      curDist = startDist;
            Vector3    curPos;
            float      curF;
            Vector3    curTan    = Vector3.zero;
            Vector3    curUp     = Vector3.zero;
            List <int> softEdges = new List <int>();



            int dead = 100000;

            raster.Resolution = Mathf.Max(raster.Resolution, 2);
            switch (raster.Mode)
            {
            case CGDataRequestRasterization.ModeEnum.Even:
                #region --- Even ---
                // we advance the spline using a fixed distance

                bool dupe = false;
                // we have at least one Material Group
                SamplePointsMaterialGroup grp = new SamplePointsMaterialGroup(materialID);
                // and at least one patch within that group
                SamplePointsPatch patch = new SamplePointsPatch(0);
                var clampMode           = (data.Closed) ? CurvyClamping.Loop : CurvyClamping.Clamp;

                while (curDist <= endDist && --dead > 0)
                {
                    tf     = spline.DistanceToTF(spline.ClampDistance(curDist, clampMode));
                    curPos = (UseCache) ? spline.InterpolateFast(tf) : spline.Interpolate(tf);
                    curF   = (curDist - startDist) / data.Length;//curDist / endDist;
                    if (Mathf.Approximately(1, curF))
                    {
                        curF = 1;
                    }

                    pos.Add(curPos);
                    relF.Add(curF);
                    sourceF.Add(curDist / spline.Length);
                    if (fullPath)     // add path values
                    {
                        curTan = (UseCache) ? spline.GetTangentFast(tf) : spline.GetTangent(tf, curPos);
                        curUp  = spline.GetOrientationUpFast(tf);
                        tan.Add(curTan);
                        up.Add(curUp);
                    }
                    if (dupe)     // HardEdge, IncludeCP, MaterialID changes etc. need an extra vertex
                    {
                        pos.Add(curPos);
                        relF.Add(curF);
                        sourceF.Add(curDist / spline.Length);
                        if (fullPath)
                        {
                            tan.Add(curTan);
                            up.Add(curUp);
                        }
                        dupe = false;
                    }
                    // Advance
                    curDist += stepDist;

                    // Check next Sample Point's options. If the next point would be past a CP with options
                    if (optionsSegs.Count > 0 && curDist >= optionsSegs[0].Distance)
                    {
                        if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                        {
                            extendedUVData.Add(new SamplePointUData(pos.Count, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                        }
                        // clamp point at CP and maybe duplicate the next sample point
                        curDist = optionsSegs[0].Distance;
                        dupe    = optionsSegs[0].HardEdge || optionsSegs[0].MaterialID != grp.MaterialID || (options.CheckExtendedUV && optionsSegs[0].UVEdge);
                        // end the current patch...
                        if (dupe)
                        {
                            patch.End = pos.Count;
                            grp.Patches.Add(patch);
                            // if MaterialID changes, we start a new MaterialGroup
                            if (grp.MaterialID != optionsSegs[0].MaterialID)
                            {
                                data.MaterialGroups.Add(grp);
                                grp = new SamplePointsMaterialGroup(optionsSegs[0].MaterialID);
                            }
                            // in any case we start a new patch
                            patch = new SamplePointsPatch(pos.Count + 1);
                            if (!optionsSegs[0].HardEdge)
                            {
                                softEdges.Add(pos.Count + 1);
                            }
                            // Extended UV
                            if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                            {
                                extendedUVData.Add(new SamplePointUData(pos.Count + 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                            }
                        }
                        // and remove the CP from the options
                        optionsSegs.RemoveAt(0);
                    }

                    // Ensure last sample point position is at the desired end distance
                    if (curDist > endDist && curF < 1)     // next loop curF will be 1
                    {
                        curDist = endDist;
                    }
                }
                if (dead <= 0)
                {
                    Debug.LogError("[Curvy] He's dead, Jim! Deadloop in SplineInputModuleBase.GetSplineData (Even)! Please send a bug report!");
                }
                // store the last open patch
                patch.End = pos.Count - 1;
                grp.Patches.Add(patch);
                // ExplicitU on last Vertex?
                //if (optionsSegs.Count > 0 && optionsSegs[0].UVShift)
                //    extendedUVData.Add(new SamplePointUData(pos.Count - 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                // if path is closed and no hard edges involved, we need to smooth first normal
                if (data.Closed && !spline[0].GetMetadata <MetaCGOptions>(true).HardEdge)
                {
                    softEdges.Add(0);
                }
                data.MaterialGroups.Add(grp);
                // fill data
                data.SourceF  = sourceF.ToArray();
                data.F        = relF.ToArray();
                data.Position = pos.ToArray();
                if (fullPath)
                {
                    ((CGPath)data).Direction = tan.ToArray();
                    data.Normal = up.ToArray();
                }
                #endregion
                break;

            case CGDataRequestRasterization.ModeEnum.Optimized:
                #region --- Optimized ---
                dupe = false;
                // we have at least one Material Group
                grp = new SamplePointsMaterialGroup(materialID);
                // and at least one patch within that group
                patch = new SamplePointsPatch(0);
                float stepSizeTF = stepDist / spline.Length;

                float maxAngle = raster.AngleThreshold;
                float stopAt;
                bool  atStopPoint;
                curPos = spline.Interpolate(tf);
                curTan = spline.GetTangent(tf, curPos);

                var addPoint = new System.Action <float>((float f) =>
                {
                    sourceF.Add(curDist / spline.Length);
                    pos.Add(curPos);
                    relF.Add((curDist - startDist) / data.Length);
                    if (fullPath)
                    {
                        tan.Add(curTan);
                        up.Add(spline.GetOrientationUpFast(f));
                    }
                });

                while (tf < endTF && dead-- > 0)
                {
                    addPoint(tf % 1);

                    // Advance
                    stopAt = (optionsSegs.Count > 0) ? optionsSegs[0].TF : endTF;

                    atStopPoint = spline.MoveByAngleExtINTERNAL(ref tf, Generator.MinDistance, maxStep, maxAngle, out curPos, out curTan, out stepDist, stopAt, data.Closed, stepSizeTF);
                    curDist    += stepDist;
                    if (Mathf.Approximately(tf, endTF) || tf > endTF)
                    {
                        curDist = endDist;
                        endTF   = (data.Closed) ? DTMath.Repeat(endTF, 1) : Mathf.Clamp01(endTF);
                        curPos  = spline.Interpolate(endTF);
                        if (fullPath)
                        {
                            curTan = spline.GetTangent(endTF, curPos);
                        }
                        addPoint(endTF);
                        break;
                    }
                    if (atStopPoint)
                    {
                        if (optionsSegs.Count > 0)
                        {
                            if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                            {
                                extendedUVData.Add(new SamplePointUData(pos.Count, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                            }
                            // clamp point at CP and maybe duplicate the next sample point
                            curDist = optionsSegs[0].Distance;
                            maxStep = (optionsSegs[0].MaxStepDistance);
                            dupe    = optionsSegs[0].HardEdge || optionsSegs[0].MaterialID != grp.MaterialID || (options.CheckExtendedUV && optionsSegs[0].UVEdge);
                            if (dupe)
                            {
                                // end the current patch...
                                patch.End = pos.Count;
                                grp.Patches.Add(patch);
                                // if MaterialID changes, we start a new MaterialGroup
                                if (grp.MaterialID != optionsSegs[0].MaterialID)
                                {
                                    data.MaterialGroups.Add(grp);
                                    grp = new SamplePointsMaterialGroup(optionsSegs[0].MaterialID);
                                }


                                // in any case we start a new patch
                                patch = new SamplePointsPatch(pos.Count + 1);
                                if (!optionsSegs[0].HardEdge)
                                {
                                    softEdges.Add(pos.Count + 1);
                                }
                                // Extended UV
                                if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                                {
                                    extendedUVData.Add(new SamplePointUData(pos.Count + 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                                }
                                addPoint(tf);
                            }
                            // and remove the CP from the options
                            optionsSegs.RemoveAt(0);
                        }
                        else
                        {
                            addPoint(tf);
                            break;
                        }
                    }
                }
                if (dead <= 0)
                {
                    Debug.LogError("[Curvy] He's dead, Jim! Deadloop in SplineInputModuleBase.GetSplineData (Optimized)! Please send a bug report!");
                }
                // store the last open patch
                patch.End = pos.Count - 1;
                grp.Patches.Add(patch);
                // ExplicitU on last Vertex?
                if (optionsSegs.Count > 0 && optionsSegs[0].UVShift)
                {
                    extendedUVData.Add(new SamplePointUData(pos.Count - 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                }
                // if path is closed and no hard edges involved, we need to smooth first normal
                if (data.Closed && !spline[0].GetMetadata <MetaCGOptions>(true).HardEdge)
                {
                    softEdges.Add(0);
                }
                data.MaterialGroups.Add(grp);
                // fill data
                data.SourceF  = sourceF.ToArray();
                data.F        = relF.ToArray();
                data.Position = pos.ToArray();
                data.Bounds   = spline.Bounds;

                if (fullPath)
                {
                    ((CGPath)data).Direction = tan.ToArray();
                    data.Normal = up.ToArray();
                }
                #endregion
                break;
            }
            data.Map = (float[])data.F.Clone();
            if (!fullPath)
            {
                data.RecalculateNormals(softEdges);
                if (options && options.CheckExtendedUV)
                {
                    CalculateExtendedUV(spline, startTF, endTF, extendedUVData, data);
                }
            }
            return(data);
        }
        void DoInterpolate()
        {
            if (!mSpline.IsInitialized)
            {
                return;
            }

            System.Type metaDataType;
            {
                if (String.IsNullOrEmpty(MetaDataType.Value))
                {
                    metaDataType = null;
                }
                else
                {
#if NETFX_CORE
                    Type[] knownTypes = this.GetType().GetAllTypes();
#else
                    Type[] knownTypes = TypeExt.GetLoadedTypes();
#endif
                    metaDataType = knownTypes.FirstOrDefault(t => t.FullName == MetaDataType.Value);
                }
            }

            bool calc = !Input.IsNone;
            if (calc)
            {
                float f = (UseWorldUnits.Value) ? mSpline.DistanceToTF(Input.Value) : Input.Value;

                if (StorePosition.IsNone == false)
                {
                    StorePosition.Value = (UseCache.Value) ? mSpline.InterpolateFast(f) : mSpline.Interpolate(f);
                }

                if (StoreTangent.IsNone == false)
                {
                    StoreTangent.Value = mSpline.GetTangent(f);
                }

                if (StoreUpVector.IsNone == false)
                {
                    StoreUpVector.Value = mSpline.GetOrientationUpFast(f);
                }

                if (StoreRotation.IsNone == false)
                {
                    StoreRotation.Value = (StoreUpVector.IsNone) ? mSpline.GetOrientationFast(f) : Quaternion.LookRotation(mSpline.GetTangent(f), StoreUpVector.Value);
                }

                if (StoreScale.IsNone == false)
                {
                    float localF;
                    CurvySplineSegment segment          = mSpline.TFToSegment(f, out localF);
                    CurvySplineSegment nextControlPoint = segment.Spline.GetNextControlPoint(segment);
                    if (ReferenceEquals(segment, null) == false)
                    {
                        StoreScale.Value = nextControlPoint
                            ? Vector3.Lerp(segment.transform.lossyScale, nextControlPoint.transform.lossyScale, localF)
                            : segment.transform.lossyScale;
                    }
                    else
                    {
                        StoreScale.Value = Vector3.zero;
                    }
                }

                if (StoreTF.IsNone == false)
                {
                    StoreTF.Value = f;
                }

                if (StoreDistance.IsNone == false)
                {
                    StoreDistance.Value = (UseWorldUnits.Value) ? Input.Value : mSpline.TFToDistance(f);
                }
                if (metaDataType != null)
                {
                    if (metaDataType.IsSubclassOf(typeof(CurvyMetadataBase)) == false)
                    {
                        //this if statement's branch does not exclude classes inheriting from CurvyMetadataBase but not from CurvyInterpolatableMetadataBase, but that's ok, those classes are handled below
                        Debug.LogError("Meta data type " + metaDataType.FullName + " should be a subclass of CurvyInterpolatableMetadataBase<T>");
                    }
                    else
                    {
                        if (StoreMetadata.IsNone == false)
                        {
                            MethodInfo genericMethodInfo = mSpline.GetType().GetMethod("GetMetadata").MakeGenericMethod(metaDataType);
                            StoreMetadata.Value = (Object)genericMethodInfo.Invoke(mSpline, new System.Object[] { f });
                        }
                        if (StoreInterpolatedMetadata.IsNone == false)
                        {
                            Type argumentType = GetInterpolatableMetadataGenericType(metaDataType);

                            if (argumentType == null)
                            {
                                Debug.LogError("Meta data type " + metaDataType.FullName + " should be a subclass of CurvyInterpolatableMetadataBase<T>");
                            }
                            else
                            {
                                MethodInfo genericMethodInfo = mSpline.GetType().GetMethod("GetInterpolatedMetadata").MakeGenericMethod(metaDataType, argumentType);
                                StoreInterpolatedMetadata.SetValue(genericMethodInfo.Invoke(mSpline, new System.Object[] { f }));
                            }
                        }
                    }
                }


                CurvySplineSegment seg = null;
                float segF             = 0;
                if (StoreSegment.IsNone == false)
                {
                    seg = getSegment(f, out segF);
                    StoreSegment.Value = seg.gameObject;
                }

                if (StoreSegmentF.IsNone == false)
                {
                    if (!seg)
                    {
                        seg = getSegment(f, out segF);
                    }
                    StoreSegmentF.Value = segF;
                }

                if (StoreSegmentDistance.IsNone == false)
                {
                    if (!seg)
                    {
                        seg = getSegment(f, out segF);
                    }
                    StoreSegmentDistance.Value = seg.LocalFToDistance(segF);
                }
            }
            // General
            if (StoreLength.IsNone == false)
            {
                StoreLength.Value = mSpline.Length;
            }

            if (StoreCount.IsNone == false)
            {
                StoreCount.Value = mSpline.Count;
            }
        }
        public CurvyMeshSegmentInfo(SplinePathMeshBuilder mb, float tf, float distance, Vector3 scale)
        {
            Spline = mb.Spline;
            TF = tf;
            mDistance = distance;

            Vector3 p = (mb.FastInterpolation) ? Spline.InterpolateFast(TF) : Spline.Interpolate(TF);

            if (mb.UseWorldPosition)
                Matrix = Matrix4x4.TRS(mb.Transform.InverseTransformPoint(p), Spline.GetOrientationFast(TF), scale);
            else
                Matrix = Matrix4x4.TRS(Spline.Transform.InverseTransformPoint(p), Spline.GetOrientationFast(TF), scale);
        }
        /// <summary>
        /// Builds a mesh from a spline (2D), taking interpolated points based on curvation angle
        /// </summary>
        /// <param name="spline">the spline to use</param>
        /// <param name="ignoreAxis">the axis to ignore (0=x,1=y,2=z)</param>
        /// <param name="close">True to create a mesh with triangles, False to create a vertex line mesh</param>
        /// <param name="angleDiff">the curvation angle used to interpolate points</param>
        public static Mesh CreateSplineMesh(CurvySpline spline, int ignoreAxis, bool close, float angleDiff)
        {
            float tf = 0;
            int dir = 1;
            List<Vector3> verts = new List<Vector3>();
            verts.Add(spline.Transform.worldToLocalMatrix.MultiplyPoint3x4(spline.Interpolate(0)));
            while (tf < 1) {
                verts.Add(spline.Transform.worldToLocalMatrix.MultiplyPoint3x4(spline.MoveByAngle(ref tf, ref dir, angleDiff, CurvyClamping.Clamp, 0.005f)));
            }

            return buildSplineMesh(verts.ToArray(), ignoreAxis, !close);
        }
    public void UpdateATL(ThirdPersonUserControl player, CurvySpline spline)
    {
        if (!init && spline.IsInitialized)
        {
            init = true;
            t    = spline.GetNearestPointTF(player.transform.position);

            minT = t - (buffer / spline.Length) / 2.0f;
            maxT = t + (buffer / spline.Length) / 2.0f;
        }

        if (!init)
        {
            return;
        }

        //print ("spline name = " + spline.name);

        float playerT = spline.GetNearestPointTF(player.transform.position);

        //print ("playerT = " + playerT);
        //AxKDebugLines.AddSphere (player.transform.position, 0.3f, Color.green);
        //AxKDebugLines.AddSphere (spline.Interpolate (player.transform.position), 0.3f, Color.magenta);
        //AxKDebugLines.AddSphere (spline.Interpolate (playerT), 0.3f, Color.blue);

        if (playerT > maxT)
        {
            maxT = playerT;
            minT = maxT - (buffer / spline.Length);
            t    = playerT;
        }
        else if (playerT < minT)
        {
            minT = playerT;
            maxT = minT + (buffer / spline.Length);
            t    = playerT;
        }

        //AxKDebugLines.AddSphere (spline.Interpolate (maxT), 0.3f, Color.green);
        //AxKDebugLines.AddSphere (spline.Interpolate (minT), 0.3f, Color.magenta);

        splineUp      = spline.GetRotatedUpFast(t, 0);
        splineForward = spline.GetTangent(t);
        splineRight   = Vector3.Cross(splineUp, splineForward);
        //print ("offset = " + offset);

        Vector3 rise = splineUp * offset.y + splineForward * offset.z + splineRight * offset.x * Mathf.Sin(Mathf.Sqrt(Time.time));

        float   targetPositionT = t + offsetCam / spline.Length;
        Vector3 targetPosition  = spline.Interpolate(targetPositionT) + rise;

        float   lookPositionT = t - offsetLook / spline.Length;
        Vector3 lookPosition  = spline.Interpolate(lookPositionT);

        targetPosition = ((targetPosition * 4f) + player.transform.position) / 5f;

        if (CUbool)
        {
            lookPosition   = player.transform.position + player.transform.up * 2.55f;
            targetPosition = lookPosition + player.transform.forward * .4f;
            //print ("in bool");
        }
        else if (falling)
        {
            lookPosition   = player.transform.position;
            targetPosition = transform.position;
        }

        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth);
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation((lookPosition - transform.position).normalized), Time.deltaTime * smooth);
    }
Beispiel #30
0
    public void UpdateATL(List <BoidFlocking> _boids, BoidLord boidLord, ThirdPersonUserControl player, CurvySpline spline, Crosshair crosshair)
    {
        if (destroyMe)
        {
            boidLord.RemoveBoid(this);
        }

        alignment  = ComputeAlignment(_boids, boidLord) * boidLord.alignmentStrength;
        cohesion   = ComputeCohesion(_boids, boidLord) * boidLord.cohesionStrength;
        separation = ComputeSeparation(_boids, boidLord) * boidLord.seperationStrength;

        Vector3 wiggle = new Vector3(Mathf.Sin(Time.timeSinceLevelLoad + seed[2]), Mathf.Sin(Time.timeSinceLevelLoad + seed[1]), Mathf.Sin(Time.timeSinceLevelLoad + seed[0]));

        // add variation of target
        if ((iterator + 1) % 3 == 0)
        {
            Vector3 offset = crosshair.transform.position - player.transform.position;
            target = crosshair.transform.position + offset * 5.0f + crosshair.transform.right * Mathf.Sin(Time.timeSinceLevelLoad + seed[0]) * 5.0f;
        }
        else if ((iterator + 1) % 2 == 0)
        {
            float d = Vector3.Distance(player.transform.position, Camera.main.transform.position);
            target  = Camera.main.transform.position + Camera.main.transform.forward * d * 7.0f + Camera.main.transform.up * d * 3.0f;
            target += Camera.main.transform.right * Mathf.Cos(Time.timeSinceLevelLoad + seed[2]) * 15.0f;
        }
        else
        {
            float t = Camera.main.GetComponent <CameraController_three>().GetPlayerT();
            //interpolate position on spline behind player
            target = spline.Interpolate(t * .6f);
            //vectors are taken from point on spline where the player is
            target += Camera.main.GetComponent <CameraController_three>().GetSplineUp() * 8.0f;
            target += Camera.main.GetComponent <CameraController_three>().GetSplineRight() * Mathf.Sin(Time.timeSinceLevelLoad + seed[1]) * 20.0f;
        }

        target -= transform.position; // make target position a vector from this boid to that position
        Vector3 velocityChange = alignment + cohesion + separation + target;

        GetComponent <Rigidbody>().AddForce(velocityChange * Time.deltaTime * 0.3f, ForceMode.VelocityChange);    // changed from Acceleration
        GetComponent <Rigidbody>().drag = 0.8f;

        Quaternion look = Quaternion.LookRotation(player.transform.position - transform.position);

        GetComponent <Rigidbody>().MoveRotation(Quaternion.Slerp(transform.rotation, look, Time.deltaTime * 3.0f));
        GetComponent <Rigidbody>().AddForce(transform.forward * 0.2f, ForceMode.VelocityChange);

        //AxKDebugLines.AddLine(transform.position, transform.position + cohesion, Color.cyan, 0);
        //AxKDebugLines.AddLine(transform.position, transform.position + alignment, Color.green, 0);
        //AxKDebugLines.AddLine(transform.position, transform.position + separation, Color.yellow, 0);

        /*
         * if ((iterator+1) % 3 == 0)
         * {
         *  AxKDebugLines.AddLine(transform.position, transform.position + target, Color.white, 0);
         * }
         * else if ((iterator+1) % 2 == 0)
         * {
         *  AxKDebugLines.AddLine(transform.position, transform.position + target, Color.red, 0);
         * }
         * else
         * {
         *  AxKDebugLines.AddLine(transform.position, transform.position + target, Color.black, 0);
         * }
         */
    }
Beispiel #31
0
    public void UpdateATL(ThirdPersonUserControl player, CurvySpline spline)
    {
        if (!init && spline.IsInitialized)
        {
            init = true;
        }

        if (!init)
        {
            return;
        }

        if (!Camera.main.GetComponent <CameraController_three> ().CUbool&& !wasdDone)
        {
            //player.GetComponentInChildren<MakeMesh> (true).enabled = true;
            MakeTextGO("TO MOVE HOLD DOWN WASD");              //0-17 before "W"
            wasdDone = true;
        }
        if (Input.GetKeyDown(KeyCode.W) && !wPressed)
        {
            SwapCharGO(' ', 14);             // replace W with a space
            wPressed = true;
        }
        if (Input.GetKeyDown(KeyCode.A) && !aPressed)
        {
            SwapCharGO(' ', 15);
            aPressed = true;
        }
        if (Input.GetKeyDown(KeyCode.S) && !sPressed)
        {
            SwapCharGO(' ', 16);
            sPressed = true;
        }
        if (Input.GetKeyDown(KeyCode.D) && !dPressed)
        {
            SwapCharGO(' ', 17);
            dPressed = true;
        }

        // conditionals for which words to show
        if (wPressed && sPressed && aPressed && dPressed && !wasdCleared)
        {
            Clear();
            wasdCleared = true;
        }
        if (player.GetComponent <ThirdPersonCharacter> ().SeenGun() && !qDone && wasdCleared)         //must evade intro wide with gun in view
        {
            MakeTextGO("PRESS Q TO PICKUP");
            qDone = true;
        }
        if (player.GetComponent <ThirdPersonCharacter> ().m_pickup == true && !mouseAimDone)
        {
            MakeTextGO("PRESS LEFT MOUSE DOWN TO AIM");
            mouseAimDone = true;
        }
        if (player.GetComponent <ThirdPersonCharacter> ().m_doneAim == true && !mouseFireDone)
        {
            MakeTextGO("RELEASE LEFT MOUSE TO FIRE");
            mouseFireDone = true;
            //StartCoroutine (Fade (4.0f)); //do on fireFlag below
        }
        if (player.GetComponent <ThirdPersonCharacter> ().m_fireFlag == true & !fireCleared)
        {
            Clear();
            fireCleared = true;
        }

        float t = spline.GetNearestPointTF(player.transform.position);

        //AxKDebugLines.AddSphere (spline.Interpolate (maxT), 0.3f, Color.green);
        //AxKDebugLines.AddSphere (spline.Interpolate (minT), 0.3f, Color.magenta);

        Vector3 splineUp      = spline.GetRotatedUpFast(t, 0);
        Vector3 splineForward = spline.GetTangent(t);
        Vector3 splineRight   = Vector3.Cross(splineUp, splineForward);

        //Vector3 rise = splineRight * offset.x + splineUp * offset.y + splineForward * offset.z;

        Vector3 lookPosition = Camera.main.transform.position;
        //Vector3 targetPosition = player.transform.position + player.transform.right * 0.8f * textLength / 4 + player.transform.up * 4.0f - player.transform.forward * 3.0f;
        Vector3 targetPosition = spline.Interpolate(t) + splineRight * 0.8f * textLength / 3 + splineUp * 4.0f - splineForward * 3.0f;

        //AxKDebugLines.AddSphere (lookPosition, .1f, Color.red);
        //AxKDebugLines.AddSphere (targetPosition, .1f, Color.blue);

        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth);
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation((lookPosition - transform.position).normalized), Time.deltaTime * smooth);
    }
        protected CGData GetSplineData(CurvySpline spline, bool fullPath, CGDataRequestRasterization raster, CGDataRequestMetaCGOptions options)
        {
            if (spline == null || spline.Count == 0)
                return null;
            List<ControlPointOption> optionsSegs = new List<ControlPointOption>();
            int materialID = 0;
            float maxStep = float.MaxValue;

            var data = (fullPath) ? new CGPath() : new CGShape();
            // calc start & end point (distance)
            float startDist;
            float endDist;
            getRange(spline, raster, out startDist, out endDist);
            
            float stepDist = (endDist - startDist) / (raster.Resolution - 1);
            data.Length = endDist - startDist;

            // initialize with start TF
            float tf = spline.DistanceToTF(startDist);
            float startTF = tf;
            float endTF = (endDist > spline.Length && spline.Closed) ? spline.DistanceToTF(endDist - spline.Length) + 1 : spline.DistanceToTF(endDist);

            // Set properties
            data.SourceIsManaged = IsManagedResource(spline);
            data.Closed = spline.Closed;
            data.Seamless = spline.Closed && raster.Length == 1;


            if (data.Length == 0)
                return data;

            // Scan input spline and fetch a list of control points that provide special options (Hard Edge, MaterialID etc...)
            if (options)
                optionsSegs = CGUtility.GetControlPointsWithOptions(options, 
                                                                    spline, 
                                                                    startDist, 
                                                                    endDist, 
                                                                    raster.Mode == CGDataRequestRasterization.ModeEnum.Optimized, 
                                                                    out materialID, 
                                                                    out maxStep);

            // Setup vars
            List<SamplePointUData> extendedUVData = new List<SamplePointUData>();
            List<Vector3> pos = new List<Vector3>();
            List<float> relF = new List<float>();
            List<float> sourceF = new List<float>();
            List<Vector3> tan = new List<Vector3>();
            List<Vector3> up = new List<Vector3>();
            float curDist = startDist;
            Vector3 curPos;
            float curF;
            Vector3 curTan = Vector3.zero;
            Vector3 curUp = Vector3.zero;
            List<int> softEdges = new List<int>();




            int dead = 100000;
            raster.Resolution = Mathf.Max(raster.Resolution, 2);
            switch (raster.Mode)
            {
                case CGDataRequestRasterization.ModeEnum.Even:
                    #region --- Even ---
                    // we advance the spline using a fixed distance
                    
                    bool dupe = false;
                    // we have at least one Material Group
                    SamplePointsMaterialGroup grp = new SamplePointsMaterialGroup(materialID);
                    // and at least one patch within that group
                    SamplePointsPatch patch = new SamplePointsPatch(0);
                    var clampMode=(data.Closed) ? CurvyClamping.Loop : CurvyClamping.Clamp;
                    
                    while (curDist <= endDist && --dead>0)
                    {
                        
                        tf = spline.DistanceToTF(spline.ClampDistance(curDist, clampMode));
                        curPos = spline.Interpolate(tf);
                        curF = (curDist-startDist) / data.Length;//curDist / endDist;
                        if (Mathf.Approximately(1, curF))
                            curF = 1;
                        
                        pos.Add(curPos);
                        relF.Add(curF);
                        sourceF.Add(curDist / spline.Length);
                        if (fullPath) // add path values
                        {
                            curTan = spline.GetTangent(tf,curPos);
                            curUp = spline.GetOrientationUpFast(tf);
                            tan.Add(curTan);
                            up.Add(curUp);
                        }
                        if (dupe) // HardEdge, IncludeCP, MaterialID changes etc. need an extra vertex
                        {
                            pos.Add(curPos);
                            relF.Add(curF);
                            sourceF.Add(curDist / spline.Length);
                            if (fullPath)
                            {
                                tan.Add(curTan);
                                up.Add(curUp);
                            }
                            dupe = false;
                        }
                        // Advance
                        curDist += stepDist;

                        // Check next Sample Point's options. If the next point would be past a CP with options
                        if (optionsSegs.Count > 0 && curDist >= optionsSegs[0].Distance)
                        {
                            if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                                extendedUVData.Add(new SamplePointUData(pos.Count, optionsSegs[0].UVEdge,optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                            // clamp point at CP and maybe duplicate the next sample point
                            curDist = optionsSegs[0].Distance;
                            dupe = optionsSegs[0].HardEdge || optionsSegs[0].MaterialID != grp.MaterialID || (options.CheckExtendedUV && optionsSegs[0].UVEdge);
                            // end the current patch...
                            if (dupe)
                            {
                                patch.End = pos.Count;
                                grp.Patches.Add(patch);
                                // if MaterialID changes, we start a new MaterialGroup
                                if (grp.MaterialID != optionsSegs[0].MaterialID)
                                {
                                    data.MaterialGroups.Add(grp);
                                    grp = new SamplePointsMaterialGroup(optionsSegs[0].MaterialID);
                                }
                                // in any case we start a new patch
                                patch = new SamplePointsPatch(pos.Count + 1);
                                if (!optionsSegs[0].HardEdge)
                                    softEdges.Add(pos.Count + 1);
                                // Extended UV
                                if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                                    extendedUVData.Add(new SamplePointUData(pos.Count + 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                            }
                            // and remove the CP from the options
                            optionsSegs.RemoveAt(0);
                        }

                        // Ensure last sample point position is at the desired end distance
                        if (curDist > endDist && curF < 1) // next loop curF will be 1
                            curDist = endDist;
                    }
                    if (dead<= 0)
                        Debug.LogError("[Curvy] He's dead, Jim! Deadloop in SplineInputModuleBase.GetSplineData (Even)! Please send a bug report!");
                    // store the last open patch
                    patch.End = pos.Count - 1;
                    grp.Patches.Add(patch);
                    // ExplicitU on last Vertex?
                    //if (optionsSegs.Count > 0 && optionsSegs[0].UVShift)
                    //    extendedUVData.Add(new SamplePointUData(pos.Count - 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                    // if path is closed and no hard edges involved, we need to smooth first normal
                    if (data.Closed && !spline[0].GetMetadata<MetaCGOptions>(true).HardEdge)
                        softEdges.Add(0);
                    data.MaterialGroups.Add(grp);
                    // fill data
                    data.SourceF = sourceF.ToArray();
                    data.F = relF.ToArray();
                    data.Position = pos.ToArray();
                    if (fullPath)
                    {
                        ((CGPath)data).Direction = tan.ToArray();
                        data.Normal = up.ToArray();
                    }
                    #endregion
                    break;
                case CGDataRequestRasterization.ModeEnum.Optimized:
                    #region --- Optimized ---
                    dupe = false;
                    // we have at least one Material Group
                    grp = new SamplePointsMaterialGroup(materialID);
                    // and at least one patch within that group
                    patch = new SamplePointsPatch(0);
                    float stepSizeTF = stepDist / spline.Length;

                    float maxAngle = raster.AngleThreshold;
                    float stopAt;
                    bool atStopPoint;
                    curPos = spline.Interpolate(tf);
                    curTan = spline.GetTangent(tf, curPos);

                    var addPoint = new System.Action<float>((float f) =>
                    {
                        sourceF.Add(curDist/spline.Length);
                        pos.Add(curPos);
                        relF.Add((curDist -startDist) / data.Length);
                        if (fullPath)
                        {
                            tan.Add(curTan);
                            up.Add(spline.GetOrientationUpFast(f));
                        }
                    });
                    
                    while (tf < endTF && dead-- > 0)
                    {
                        addPoint(tf%1);

                        // Advance
                        stopAt = (optionsSegs.Count > 0) ? optionsSegs[0].TF : endTF;
                        
                        atStopPoint = spline.MoveByAngleExtINTERNAL(ref tf, Generator.MinDistance, maxStep, maxAngle, out curPos, out curTan, out stepDist, stopAt, data.Closed,stepSizeTF);
                        curDist += stepDist;
                        if (Mathf.Approximately(tf, endTF) || tf > endTF)
                        {
                            curDist = endDist;
                            endTF = (data.Closed) ? DTMath.Repeat(endTF,1) : Mathf.Clamp01(endTF);
                            curPos = spline.Interpolate(endTF);
                            if (fullPath)
                                curTan = spline.GetTangent(endTF, curPos);
                            addPoint(endTF);
                            break;
                        }
                        if (atStopPoint)
                        {
                            if (optionsSegs.Count > 0)
                            {
                                if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                                    extendedUVData.Add(new SamplePointUData(pos.Count, optionsSegs[0].UVEdge,optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                                // clamp point at CP and maybe duplicate the next sample point
                                curDist = optionsSegs[0].Distance;
                                maxStep = (optionsSegs[0].MaxStepDistance);
                                dupe = optionsSegs[0].HardEdge || optionsSegs[0].MaterialID != grp.MaterialID || (options.CheckExtendedUV && optionsSegs[0].UVEdge);
                                if (dupe)
                                {
                                    // end the current patch...
                                    patch.End = pos.Count;
                                    grp.Patches.Add(patch);
                                    // if MaterialID changes, we start a new MaterialGroup
                                    if (grp.MaterialID != optionsSegs[0].MaterialID)
                                    {
                                        data.MaterialGroups.Add(grp);
                                        grp = new SamplePointsMaterialGroup(optionsSegs[0].MaterialID);
                                    }
                                    
                                    
                                    // in any case we start a new patch
                                    patch = new SamplePointsPatch(pos.Count + 1);
                                    if (!optionsSegs[0].HardEdge)
                                        softEdges.Add(pos.Count + 1);
                                    // Extended UV
                                    if (optionsSegs[0].UVEdge || optionsSegs[0].UVShift)
                                        extendedUVData.Add(new SamplePointUData(pos.Count+1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                                    addPoint(tf);
                                }
                                // and remove the CP from the options
                                optionsSegs.RemoveAt(0);
                                
                            }
                            else
                            {
                                addPoint(tf);
                                break;
                            }
                        }

                    }
                    if (dead <= 0)
                        Debug.LogError("[Curvy] He's dead, Jim! Deadloop in SplineInputModuleBase.GetSplineData (Optimized)! Please send a bug report!");
                    // store the last open patch
                    patch.End = pos.Count - 1;
                    grp.Patches.Add(patch);
                    // ExplicitU on last Vertex?
                    if (optionsSegs.Count > 0 && optionsSegs[0].UVShift)
                        extendedUVData.Add(new SamplePointUData(pos.Count - 1, optionsSegs[0].UVEdge, optionsSegs[0].FirstU, optionsSegs[0].SecondU));
                    // if path is closed and no hard edges involved, we need to smooth first normal
                    if (data.Closed && !spline[0].GetMetadata<MetaCGOptions>(true).HardEdge)
                        softEdges.Add(0);
                    data.MaterialGroups.Add(grp);
                    // fill data
                    data.SourceF = sourceF.ToArray();
                    data.F = relF.ToArray();
                    data.Position = pos.ToArray();
                    data.Bounds = spline.Bounds;
                    
                    if (fullPath)
                    {
                        ((CGPath)data).Direction = tan.ToArray();
                        data.Normal = up.ToArray();
                    }
                    #endregion
                    break;
            }
            data.Map = (float[])data.F.Clone();
            if (!fullPath)
            {
                data.RecalculateNormals(softEdges);
                if (options && options.CheckExtendedUV)
                    CalculateExtendedUV(spline,startTF,endTF,extendedUVData, data);
            }
            return data;
        }