Inheritance: MonoBehaviour
コード例 #1
0
	void OnSceneGUI()
	{
		_spline = target as BezierSpline;
		_splineT = _spline.transform;
		_splineR = Tools.pivotRotation == PivotRotation.Local ? _splineT.rotation : Quaternion.identity;

		// Draw curves
		Vector3 p0 = ShowPoint(0);
		for (int i = 1; i < _spline.ControlPointCount; i += 3) {
			Vector3 p1 = ShowPoint(i);
			Vector3 p2 = ShowPoint(i + 1);
			Vector3 p3 = ShowPoint(i + 2);

			Handles.color = Color.gray;
			Handles.DrawLine(p0, p1);
			Handles.DrawLine(p2, p3);

			Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
			p0 = p3;
		}

		// Show velocity
		if(_spline.showVelocity)
		{
			Vector3 lineStart = _spline.GetPoint(0f);
			Handles.color = Color.green;
			Handles.DrawLine(lineStart, lineStart + _spline.GetDirection(0f));

			int steps = _spline.numIterations * _spline.CurveCount;
			for (int i = 1; i <= steps; i++) {
				Vector3 lineEnd = _spline.GetPoint(i / (float)steps);
				Handles.DrawLine(lineEnd, lineEnd + _spline.GetDirection(i / (float)steps));
			}
		}
	}
コード例 #2
0
ファイル: SubTrackGroup.cs プロジェクト: mANDROID99/IaS
 public SubTrackGroup(string id, BezierSpline spline, List<SubTrackNode> nodes)
 {
     Spline = spline;
     Nodes = nodes;
     Id = id;
     foreach (SubTrackNode node in nodes) node.Group = this;
 }
コード例 #3
0
ファイル: TrackExtruder.cs プロジェクト: mANDROID99/IaS
        public Mesh ExtrudeAlong(BezierSpline spline, Vector3 down)
        {
            MeshBuilder meshBuilder = new MeshBuilder();
            meshBuilder.BeforeNext(Matrix4x4.identity, new Vector3());

            Vector3 lastTangent = spline.GetFirstDerivative(0, spline.pts[0]);
            Quaternion quat = Quaternion.LookRotation(lastTangent, -down);
            Vector3 up = down;
            Vertex[] lastVerts = null;

            for(int i = 0; i < spline.pts.Length; i ++)
            {
                BezierSpline.BezierPoint pt = spline.pts[i];
                if (Vector3.Distance(pt.startPos, pt.endPos) > 0.001f)
                {

                    int subdivisions = pt.numSubdivisions;

                    for (int div = 0; div <= subdivisions; div++)
                    {
                        float t = div / (float)pt.numSubdivisions;
                        Vector3 ptT = spline.GetPoint(t, pt);
                        Vector3 tangent = spline.GetFirstDerivative(t, pt).normalized;
                        quat = Quaternion.FromToRotation(lastTangent, tangent) * quat;

                        lastVerts = BuildNextSection(meshBuilder, ptT, tangent, quat, lastVerts);
                        lastTangent = tangent;
                    }
                }
            }

            AddCap(meshBuilder, new Vector3[] { lastVerts[0].position, lastVerts[2].position, lastVerts[4].position, lastVerts[6].position }, true);
            return meshBuilder.DoneCreateMesh();
        }
コード例 #4
0
    void OnSceneGUI()
    {
        b_spline = target as BezierSpline;
        handleTransform = b_spline.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;

        Vector3 point0 = ShowPoint(0);
        for (int i = 1; i < b_spline.ControlPointCount; i += 3)
        {
            Vector3 point1 = ShowPoint(i);
            Vector3 point2 = ShowPoint(i + 1);
            Vector3 point3 = ShowPoint(i + 2);

            Handles.color = Color.gray;
            Handles.DrawLine(point0, point1);
            Handles.DrawLine(point2, point3);

            Handles.DrawBezier(point0, point3, point1, point2, Color.white, null, 2f);
            point0 = point3;
        }
        if (showDirections == true)
        {
            ShowDirections();
        }
    }
コード例 #5
0
ファイル: TestBezierSpline.cs プロジェクト: Joxx0r/ATF
        private void TestToStringWithCulture(CultureInfo culture)
        {
            CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = culture;
            try
            {
                string listSeparator = culture.TextInfo.ListSeparator;
                string decimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
                var o = new BezierSpline();
                var controlPoint1 = new Vec3F(1.1f, 2.2f, 3.3f);
                var controlPoint2 = new Vec3F(4.4f, 5.5f, 6.6f);
                var controlPoint3 = new Vec3F(7.7f, 8.8f, 9.9f);
                var incomingTangent = new Vec3F(-1.0f, -2.0f, -3.0f);
                var outgoingTangent = new Vec3F(1.0f, 2.0f, 3.0f);
                o.Add(new BezierPoint(controlPoint1, incomingTangent, outgoingTangent));
                o.Add(new BezierPoint(controlPoint2, incomingTangent, outgoingTangent));
                o.Add(new BezierPoint(controlPoint3, incomingTangent, outgoingTangent));

                string s = o.ToString(null, null);
                TestToStringResults(o, s, listSeparator, decimalSeparator);

                string s2 = o.ToString();
                Assert.AreEqual(s, s2);

                s = o.ToString("G", culture);
                TestToStringResults(o, s, listSeparator, decimalSeparator);

                s = o.ToString("R", culture);
                TestToStringResults(o, s, listSeparator, decimalSeparator);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = originalCulture;
            }
        }
コード例 #6
0
 public override void OnInspectorGUI()
 {
     b_spline = target as BezierSpline;
     //showDirections = GUILayout.Toggle(showDirections, "Show Direction");
     EditorGUI.BeginChangeCheck();
     showDirections = EditorGUILayout.Toggle("Show Directions", b_spline.showDirections);
     if (EditorGUI.EndChangeCheck())
     {
         Undo.RecordObject(b_spline, "Toogle Show Directions");
         EditorUtility.SetDirty(b_spline);
         b_spline.showDirections = showDirections;
     }
     EditorGUI.BeginChangeCheck();
     bool looped = EditorGUILayout.Toggle("Loop", b_spline.IsLooped);
     if (EditorGUI.EndChangeCheck())
     {
         Undo.RecordObject(b_spline, "Toogle Loop");
         EditorUtility.SetDirty(b_spline);
         b_spline.IsLooped = looped;
     }
     if (selectedIndex >= 0 && selectedIndex < b_spline.ControlPointCount)
     {
         DrawSelectedPointInspector();
     }
     if (GUILayout.Button("Add Curve"))
     {
         Undo.RecordObject(b_spline, "Add Curve");
         b_spline.AddCurve();
         EditorUtility.SetDirty(b_spline);
     }
 }
コード例 #7
0
    private void OnSceneGUI()
    {
        spline = target as BezierSpline;

        handleTransform = spline.transform;
        handleRotation = handleTransform.rotation;

        Vector3 p0 = ShowPoint (0);
        for (int i = 1; i < spline.ControlPointCount; i += 3) {
            Vector3 p1 = ShowPoint (i);
            Vector3 p2 = ShowPoint (i+1);
            Vector3 p3 = ShowPoint (i+2);

            Handles.color = Color.gray;
            Handles.DrawLine (p0, p1);
            Handles.DrawLine (p2, p3);

            Handles.DrawBezier (p0, p3, p1, p2, Color.white, null, 2f);
            p0 = p3;
        }
        //		Handles.color = Color.white;
        //		Vector3 lineStart = curve.GetPoint (0f);
        //
        //		for (int i = 1; i <= lineSteps; i++) {
        //			Vector3 lineEnd = curve.GetPoint((float) i/lineSteps);
        //			Handles.DrawLine(lineStart, lineEnd);
        //			lineStart = lineEnd;
        //		}
    }
コード例 #8
0
    private void OnSceneGUI()
    {
        spline = target as BezierSpline;
        handleTransform = spline.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ?
            handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        for (int i = 1; i < spline.GetControlPointCount(); i += 3)
        {
            Vector3 p1 = ShowPoint(i);
            Vector3 p2 = ShowPoint(i + 1);
            Vector3 p3 = ShowPoint(i + 2);

            Handles.color = Color.gray;
            Handles.DrawLine(p0, p1);
            Handles.DrawLine(p2, p3);

            Handles.color = Color.white;
            Vector3 lineStart = spline.GetPoint(i);
            for (int step = 0; step <= spline.GetSmoothness(); step++)
            {
                Vector3 lineEnd = spline.GetPoint(step / (float)spline.GetSmoothness());
                Handles.DrawLine(lineStart, lineEnd);
                lineStart = lineEnd;
            }
            //Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 5f);
            p0 = p3;
        }

        //ShowDirections();
    }
コード例 #9
0
    public override void OnInspectorGUI()
    {
        spline = target as BezierSpline;
        EditorGUI.BeginChangeCheck();
        bool loop = EditorGUILayout.Toggle("Loop", spline.Loop);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(spline, "Toogle Loop");
            EditorUtility.SetDirty(spline);
            spline.Loop = loop;
        }

        if (selectedIndex >= 0 && selectedIndex < spline.ControlPointCount)
        {
            DrawSelectedPointInspector();
        }
        if (GUILayout.Button("Add Curve"))
        {
            Undo.RecordObject(spline, "Add Curve");
            spline.AddCurve();
            EditorUtility.SetDirty(spline);
        }
        if (GUILayout.Button("Flip Spline"))
        {
            Undo.RecordObject(spline, "Add Curve");
            EditorUtility.SetDirty(spline);
            spline.ReverseSpline();
        }
    }
コード例 #10
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        spline = target as BezierSpline;

        EditorGUI.BeginChangeCheck();
        bool loop = EditorGUILayout.Toggle("Loop Last Point", spline.GetLoop());
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(spline, "Loop Last Point");
            EditorUtility.SetDirty(spline);
            spline.SetLoop(loop);
        }

        if (selectedIndex >= 0 && selectedIndex < spline.GetControlPointCount())
        {
            DrawSelectedPointInspector();
        }

        if (GUILayout.Button("Add Curve"))
        {
            Undo.RecordObject(spline, "Add Curve");
            spline.AddCurve();
            EditorUtility.SetDirty(spline);
        }

        if (GUILayout.Button("Remove Curve"))
        {
            Undo.RecordObject(spline, "Remove Curve");
            spline.RemoveCurve();
            EditorUtility.SetDirty(spline);
        }
    }
コード例 #11
0
ファイル: SplineText.cs プロジェクト: dshook/centauri-tac
 void Awake()
 {
     // Make sure I have the thigs I need to get the data to deform text
     if (m_TextComponent == null)
         m_TextComponent = gameObject.GetComponent<TextMeshPro>();
     if (vertexCurve == null)
         vertexCurve = gameObject.GetComponent<BezierSpline>();
     UpdateTextPosition();
 }
コード例 #12
0
ファイル: PointerView.cs プロジェクト: dshook/centauri-tac
        internal void init(RaycastModel rm)
        {
            raycastModel = rm;
            pointerCurve = transform.Find("PointerCurve").gameObject;
            pointerCurve.SetActive(false);

            pointerSpline = pointerCurve.GetComponent<BezierSpline>();

            cardCanvasHelper = GameObject.Find(Constants.cardCanvas).GetComponent<CardCanvasHelperView>();
        }
コード例 #13
0
ファイル: SplineTracer.cs プロジェクト: Broghain/GTO7
 // Use this for initialization
 void Start()
 {
     if (track == null)
     {
         BezierSpline[] tracks = GameObject.FindObjectsOfType<BezierSpline>();
         track = tracks[Random.Range(0, tracks.Length)];
     }
     t = 0.0f;
     transform.position = track.GetPoint(t);
     offset = Random.Range(minOffset, maxOffset);
 }
コード例 #14
0
ファイル: Curve.cs プロジェクト: ldh9451/XLE
        public BezierSpline CreateSpline()
        {
            IList<IControlPoint> points = GetChildList<IControlPoint>(Schema.bezierType.pointChild);
            BezierSpline spline = new BezierSpline();
            spline.IsClosed = GetAttribute<bool>(Schema.bezierType.isClosedAttribute);

            BezierPoint bpt = new BezierPoint();
            foreach (var cpt in points)
            {
                bpt.Position = cpt.Translation;
                spline.Add(bpt);
            }
            return spline;
        }
コード例 #15
0
ファイル: TestBezierSpline.cs プロジェクト: Joxx0r/ATF
        private void TestToStringResults(BezierSpline o, string s, string listSeparator, string decimalSeparator)
        {
            string[] results = s.Split(new[] { listSeparator }, StringSplitOptions.RemoveEmptyEntries);

            // {# of points}, {control point #1}, {cp #2}, {cp #3} where each control point has 3 vectors, each with 3 floats
            Assert.AreEqual(results.Length, 1 + 3*3*3);
            Assert.True(results[1].Contains(decimalSeparator));
            Assert.True(results[2].Contains(decimalSeparator));
            Assert.True(results[3].Contains(decimalSeparator));
            Assert.AreEqual(int.Parse(results[0]), 3); //3 control points
            Assert.AreEqual(float.Parse(results[1]), 1.1f);
            Assert.AreEqual(float.Parse(results[2]), 2.2f);
            Assert.AreEqual(float.Parse(results[3]), 3.3f);
        }
コード例 #16
0
ファイル: Guy.cs プロジェクト: cjacobwade/MonsterYumYum
    public void Initialize()
    {
        GuyManager.RegisterGuy( this );

        BezierSpline[] splines = FindObjectsOfType<BezierSpline>();
        _bezierSpline = splines[ Random.Range( 0, splines.Length ) ];

        collider2D.enabled = true;
        rigidbody2D.isKinematic = true;
        transform.position = _bezierSpline.GetPoint( 0f );

        _appliedMoveSpeed = _catchupSpeed;
        _percentAlongSpline = 0f;
        enabled = true;
    }
コード例 #17
0
	private void OnSceneGUI () {
		spline = target as BezierSpline;
		handleTransform = spline.transform;
		handleRotation = Tools.pivotRotation == PivotRotation.Local ?
			handleTransform.rotation : Quaternion.identity;
		
		Vector3 p0 = ShowPoint(0);
		for (int i = 1; i < spline.ControlPointCount; i += 3) {
			Vector3 p1 = ShowPoint(i);
			Vector3 p2 = ShowPoint(i + 1);
			Vector3 p3 = ShowPoint(i + 2);
			
			Handles.color = Color.gray;
			Handles.DrawLine(p0, p1);
			Handles.DrawLine(p2, p3);
			
			Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
			p0 = p3;
		}
		ShowDirections();
	}
コード例 #18
0
    private void OnSceneGUI()
    {
        spline = target as BezierSpline;
        handleTransform = spline.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ?
            handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        for (int i = 1; i < spline.ControlPointCount; i += 3)
        {
            Vector3 p1 = ShowPoint(1);
            Vector3 p2 = ShowPoint(2);
            Vector3 p3 = ShowPoint(3);

            Handles.color = Color.gray;
            Handles.DrawLine(p0, p1);
            Handles.DrawLine(p2, p3);
            Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
            p0 = p3;
        }

        ShowDirections();

        Handles.color = Color.white;
        Vector3 lineStart = spline.GetPoint(0f);
        Handles.color = Color.green;
        Handles.DrawLine(lineStart, lineStart + spline.GetDirection(0f));
        for (int i = 1; i <= lineSteps; i++)
        {
            Vector3 lineEnd = spline.GetPoint(i / (float)lineSteps);
            Handles.color = Color.white;
            Handles.DrawLine(lineStart, lineEnd);
            Handles.color = Color.green;
            Handles.DrawLine(lineEnd, lineEnd + spline.GetDirection(i / (float)lineSteps));
            lineStart = lineEnd;
        }
    }
コード例 #19
0
    public OrientedPoint[] GeneratePath()
    {
        BezierSpline bezierSpline = GetComponent <BezierSpline> ();

        if (bezierSpline == null)
        {
            Debug.Log("No bezier spline curve assigned to the game object");
            return(null);
        }
        int   numPoints         = (int)Mathf.Ceil(bezierSpline.GetSplineLenght() / pathIncrementSize);
        float realIncrementSize = bezierSpline.GetSplineLenght() / numPoints;


        OrientedPoint[] path = new OrientedPoint[numPoints];

        for (int i = 0; i < numPoints; i++)
        {
            path [i].position      = bezierSpline.GetPointFromParametricValue(i * realIncrementSize);
            path [i].rotation      = bezierSpline.GetOrientationFromParametricValue(i * realIncrementSize);
            path [i].cumulDistance = i * realIncrementSize;
        }

        return(path);
    }
コード例 #20
0
    // Use a spline to move from point A to point B
    public void moveBySpline(BezierSpline _spline, Vector3 _pointA, Vector3 _pointB, float _duration)
    {
        spline   = Instantiate(_spline.gameObject).GetComponent <BezierSpline>();
        duration = _duration;
        moving   = true;
        progress = 0f;

        // Compute some necessary vectors
        Vector3 splineStart = spline.GetPoint(0f);
        Vector3 splineEnd   = spline.GetPoint(1f);

        Vector3 desiredAtoB = _pointB - _pointA;
        Vector3 splineAtoB  = splineEnd - splineStart;

        // Scale as necessary
        float scale = desiredAtoB.magnitude / splineAtoB.magnitude;

        spline.transform.localScale *= scale;

        // Rotate as necessary
        Vector3     orthogonalAxis      = Vector3.Cross(desiredAtoB, splineAtoB);
        const float min_ortho_magnitude = 0.00001f;

        if (orthogonalAxis.magnitude < min_ortho_magnitude)
        {
            orthogonalAxis = Vector3.up; // TODO - is this the right default? And is this ever being called?
        }
        float angleBetween = Vector3.SignedAngle(splineAtoB, desiredAtoB, orthogonalAxis);

        // TODO - is this supposed to be around spline.transform.position? Need to move to origin first?
        spline.transform.RotateAround(spline.transform.position, orthogonalAxis, angleBetween);

        // Move starting position to pointA
        splineStart = spline.GetPoint(0f);
        spline.transform.position += transform.position - splineStart;
    }
コード例 #21
0
    private void OnSceneGUI()
    {
        spline          = target as BezierSpline;
        handleTransform = spline.transform;
        handleRotation  = Tools.pivotRotation == PivotRotation.Local ?
                          handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);

        for (int i = 1; i < spline.ControlPointCount; i += 3)
        {
            Vector3 p1 = ShowPoint(i);
            Vector3 p2 = ShowPoint(i + 1);
            Vector3 p3 = ShowPoint(i + 2);

            Handles.color = Color.gray;
            Handles.DrawLine(p0, p1);
            Handles.DrawLine(p2, p3);

            Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
            p0 = p3;
        }
        ShowDirections();
    }
コード例 #22
0
    public override void OnInspectorGUI()
    {
        spline = target as BezierSpline;
        EditorGUI.BeginChangeCheck();
        bool loop = EditorGUILayout.Toggle("Loop", spline.Loop);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(spline, "Toggle Loop");
            EditorUtility.SetDirty(spline);
            spline.Loop = loop;
        }
        if (selectedIndex >= 0 && selectedIndex < spline.ControlPointCount)
        {
            DrawSelectedPointInspector();
        }

        if (GUILayout.Button("Add Curve"))
        {
            Undo.RecordObject(spline, "Add Curve");
            spline.AddCurve();
            EditorUtility.SetDirty(spline);
        }
    }
コード例 #23
0
        private void OnSceneGUI()
        {
            BezierSpline spline         = (BezierSpline)target;
            Transform    handle         = spline.transform;
            Quaternion   handleRotation = Tools.pivotRotation == PivotRotation.Local ? handle.rotation : Quaternion.identity;

            Vector3 p0 = ShowPoint(0, spline, handle, handleRotation);

            for (int i = 1; i < spline.ControlPointCount; i += 3)
            {
                Vector3 p1 = ShowPoint(i, spline, handle, handleRotation);
                Vector3 p2 = ShowPoint(i + 1, spline, handle, handleRotation);
                Vector3 p3 = ShowPoint(i + 2, spline, handle, handleRotation);

                Handles.color = Color.gray;
                Handles.DrawLine(p0, p1);
                Handles.DrawLine(p2, p3);

                Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
                p0 = p3;
            }

            ShowDirections(spline);
        }
コード例 #24
0
    // ######################## UNITY EVENT FUNCTIONS ######################## //
    protected override void OnSceneGUI()
    {
        base.OnSceneGUI();
        _spline = target as BezierSpline;

        // draw the spline
        Vector3 p0 = ShowPoint(0, MODE_COLORS[(int)_spline.GetControlPointMode(0)]);

        for (int i = 1; i < _spline.ControlPointCount; i += 3)
        {
            Vector3 p1 = ShowPoint(i, MODE_COLORS[(int)_spline.GetControlPointMode(i)]);
            Vector3 p2 = ShowPoint(i + 1, MODE_COLORS[(int)_spline.GetControlPointMode(i + 1)]);
            Vector3 p3 = ShowPoint(i + 2, MODE_COLORS[(int)_spline.GetControlPointMode(i + 2)]);

            Handles.color = Color.gray;
            Handles.DrawLine(p0, p1);
            Handles.DrawLine(p2, p3);

            Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
            p0 = p3;
        }

        ShowDirections();
    }
コード例 #25
0
    public void GenerateTrack()
    {
        trackPoints.Clear();

        Vector3 point = Vector3.zero;

        float radiusAmount = 0f;

        centerTrackPoints = new Vector3[curvePoints];

        // Set Curves on Bezier Spline
        bezierSpline = GetComponent<BezierSpline> ();
        bezierSpline.Reset ();
        //		bezierSpline.ClearControlPoints ();
        bezierSpline.Loop = true;
        bezierSpline.OnBezierPointChanged = UpdateTrackMesh;

        for (int i = 0; i < curvePoints; i++)
        {
            radiusAmount = ((float)i / curvePoints) * (2*Mathf.PI);
            point = new Vector3(radius.x * Mathf.Cos (frequency.x * radiusAmount), 0f, radius.y * Mathf.Sin (frequency.y * radiusAmount));

            point = point * radiusSizeFactor;
            centerTrackPoints[i] = point;

            trackPoints.Add (point);

            // Set points in the Bezier curve
            if (i > 0 && i % 3 == 0)
                bezierSpline.AddCurve ();

            bezierSpline.SetControlPoint (i, point);
        }

        UpdateTrackMesh ();
    }
コード例 #26
0
ファイル: GF47CameraPathEditor.cs プロジェクト: GF47/GRT
        // 绘制贝塞尔点的面板,返回值为是否刷新检视面板
        private static bool DrawBezierPointInspector(BezierSpline bs, int index, ref int insertID, ref int removeID, ref int selectedID)
        {
            bool refreshSv = false;

            GUI.backgroundColor = index == selectedID ? Color.yellow : Color.cyan;
            if (bs != null && bs.Count > index)
            {
                EditorGUILayout.BeginVertical(EditorStyles.textField);
                BezierPoint point = bs[index];
                if (point == null)
                {
                    Undo.RecordObject(bs, "add bezier point");
                    bs[index] = new BezierPoint();
                    EditorUtility.SetDirty(bs);
                    point = bs[index];

                    refreshSv = true;
                }
                Vector3 pos = point.Position;
                pos = EditorGUILayout.Vector3Field("Postion", pos);
                if (point.Position != pos)
                {
                    point.Position = pos;

                    refreshSv = true;
                }
                EditorGUILayout.BeginHorizontal();
                point.type    = (BezierPoint.PointType)EditorGUILayout.EnumPopup("Type", point.type);
                point.Percent = EditorGUILayout.FloatField("Percent", point.Percent);
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.BeginHorizontal();
                if (selectedID == index)
                {
                    if (GUILayout.Button("UnSelect", EditorStyles.miniButtonLeft))
                    {
                        selectedID = -1; refreshSv = true;
                    }
                }
                else
                {
                    if (GUILayout.Button("Select", EditorStyles.miniButtonLeft))
                    {
                        selectedID = index; refreshSv = true;
                    }
                }
                if (GUILayout.Button("Focus", EditorStyles.miniButtonMid))
                {
                    SceneView.lastActiveSceneView.LookAt(pos);
                }
                if (GUILayout.Button("Insert", EditorStyles.miniButtonMid))
                {
                    insertID = index; refreshSv = true;
                }
                if (GUILayout.Button("Remove", EditorStyles.miniButtonRight))
                {
                    removeID = index; refreshSv = true;
                }
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.EndVertical();
            }
            GUI.backgroundColor = BackgroundColor;

            return(refreshSv);
        }
コード例 #27
0
    private void OnSceneGUI()
    {
        BezierSpline spline    = (BezierSpline)target;
        Transform    transform = spline.transform;
        Quaternion   handleRot = Tools.pivotRotation == PivotRotation.Local ? transform.rotation : Quaternion.identity;

        /* Transform points of each curve into world space */
        List <Vector3[]> worldCurves = new List <Vector3[]>();

        //foreach(Vector3[] curve in spline.curves)
        foreach (Points curve in spline.curves)
        {
            Vector3[] worldCurve = new Vector3[curve.points.Length];
            for (int i = 0; i < curve.points.Length; i++)
            {
                worldCurve[i] = transform.TransformPoint(curve.points[i]);
            }

            worldCurves.Add(worldCurve);
        }

        /* Loop through each world space curve in the spline and update handles/lines/curves for it */
        for (int i = 0; i < worldCurves.Count; i++)
        {
            Vector3[] curve = worldCurves[i];

            /* Draw handle line */
            Handles.color = i == selectedCurveIndex ? SplineUIParams.selectedHandleLineColour : SplineUIParams.handleLineColour;
            for (int j = 1; j < curve.Length; j++)
            {
                Handles.DrawLine(curve[j - 1], curve[j]);
            }

            /* show handle for and update each point on curve */
            for (int j = 0; j < curve.Length; j++)
            {
                Vector3 p = curve[j];

                //display dot button for each curve point; only display handle of selected point
                //selectedIndex must persist between OnSceneGUI() calls or the handle will only appear for one call
                float size = HandleUtility.GetHandleSize(p);
                Handles.color = SplineUIParams.handleColour;
                if (Handles.Button(p, handleRot, size * SplineUIParams.handleSize,
                                   size * SplineUIParams.handlePickSize, Handles.DotHandleCap))
                {
                    selectedCurveIndex = i;
                    selectedPointIndex = j;
                }

                //display move handle for selected point
                if (i == selectedCurveIndex && j == selectedPointIndex)
                {
                    EditorGUI.BeginChangeCheck();
                    p = Handles.DoPositionHandle(p, handleRot); //DoPositionHandle creates an editor Handle at position and rotation
                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(spline, "Move Bezier Curve Point"); //allow handle move to be undone with Undo
                        EditorUtility.SetDirty(spline);                       //set line to dirty so Unity knows a change was made and asks to save before closing etc.

                        //Transform moved world point back to local position and update selected point with it
                        Vector3 localPoint = transform.InverseTransformPoint(p);
                        spline.curves[i].points[j] = localPoint;

                        //If selected point is the last point of non-last curve in the spline, move first point of next curve to match;
                        //if selected point is the first point of non-first curve in the spline, move last point of previous curve to match
                        if (j == spline.curves[i].points.Length - 1 && i < spline.curves.Count - 1)
                        {
                            spline.curves[i + 1].points[0] = localPoint;
                        }
                        else if (j == 0 && i > 0)
                        {
                            spline.curves[i - 1].points[spline.curves[i - 1].points.Length - 1] = localPoint;
                        }
                    }
                }
            }

            /* draw curve as line segments */
            float segmentLength = SplineUIParams.GetCurveSegmentLength(curve);

            Color curveCol = i == selectedCurveIndex ? SplineUIParams.selectedCurveColour : SplineUIParams.curveColour;
            for (float t = segmentLength; t <= 1; t += segmentLength)
            {
                Handles.color = curveCol;
                Handles.DrawLine(spline.GetWorldPoint(i, t - segmentLength), spline.GetWorldPoint(i, t));

                if (showTangents)
                {
                    Handles.color = SplineUIParams.tanColour;
                    //Handles.DrawLine(spline.)
                }

                if (showNormals)
                {
                    Handles.color = SplineUIParams.normalColour;
                    //show normals
                }
            }
        }
    }
コード例 #28
0
    void ReallocateNodeOverSpline(Transform node, BezierSpline spline, int depth)
    {
        float newPosition;

        // Collide with spline that can belong to 2 possible objects, biffurcation or curve
        Curve       curve       = spline.transform.parent.GetComponent <Curve>();
        Bifurcation bifurcation = spline.transform.parent.GetComponent <Bifurcation>();

        if (curve != null)
        {// we are in a curve
            Debug.DrawLine(transform.position, nodeToFollow.position, Color.cyan);
        }

        if (bifurcation != null)
        {// we are in a bifurcation
            if (bifurcation.splines[0].isPath)
            {
                spline = bifurcation.splines[0];
            }
            else
            {
                spline = bifurcation.splines[1];
            }
        }

        newPosition           = spline.GetClosestPoint(transform.position + transform.forward * distToNode, 0.01f);
        nodeToFollow.position = spline.GetPoint(newPosition);
        nodeToFollow.rotation = spline.GetOrientation(newPosition, transform.up);

        // end or beggining of spline reached, check next/previous spline
        if (newPosition == 2)
        {     // jump to previous spline
            if (depth == 1)
            { // avoid infinite recursive loops
                nodeToFollow.position = spline.startNode.transform.position;
                nodeToFollow.rotation = spline.startNode.transform.rotation;
                return;
            }

            RaycastHit hit;

            Vector3 dir = -spline.startNode.transform.forward;
            //if (spline.startNode.reverse == true) dir *= -1;

            if (Physics.Raycast(spline.startNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30))
            {
                spline = hit.collider.transform.GetComponent <BezierSpline>();
            }
            ReallocateNodeOverSpline(nodeToFollow, spline, 1);
        }
        if (newPosition == 3)
        {     // jump to next spline
            if (depth == 1)
            { // avoid infinite recursive loops
                nodeToFollow.position = spline.endNode.transform.position;
                nodeToFollow.rotation = spline.endNode.transform.rotation;
                return;
            }

            RaycastHit hit;

            Vector3 dir = spline.endNode.transform.forward;
            //if (spline.endNode.reverse == true)
            //    dir *= -1;

            if (Physics.Raycast(spline.endNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30))
            {
                spline = hit.collider.transform.GetComponent <BezierSpline>();
            }

            ReallocateNodeOverSpline(nodeToFollow, spline, 1);
        }
    }
コード例 #29
0
 public SplineInterpolator(IEnumerable <Vector3> points)
 {
     _spline = new BezierSpline(points.ToList());
 }
コード例 #30
0
    void Awake()
    {
        float xCenterOffset = _bodyScale * (float)(_horizontalQuads - 1) / 2f;

        // Generate mesh from piece info
        MeshFilter meshFilter = GetComponent <MeshFilter>();

        List <Vector3> vertices  = new List <Vector3>();
        List <Vector2> uvs       = new List <Vector2>();
        List <int>     triangles = new List <int>();

        int appliedVerticalQuads = _verticalQuads * _bodyLength;

        for (int y = 0; y < appliedVerticalQuads; y++)
        {
            for (int x = 0; x < _horizontalQuads; x++)
            {
                vertices.Add(new Vector3(x * _bodyScale - xCenterOffset, y * _bodyScale));
                uvs.Add(new Vector2(x / (float)(_horizontalQuads - 1), y / (float)(appliedVerticalQuads - 1)));

                if (x != 0 && y != 0)
                {
                    int topRight    = y * _horizontalQuads + x;
                    int topLeft     = y * _horizontalQuads + x - 1;
                    int bottomRight = (y - 1) * _horizontalQuads + x;
                    int bottomLeft  = (y - 1) * _horizontalQuads + x - 1;

                    triangles.Add(bottomLeft);
                    triangles.Add(topLeft);
                    triangles.Add(topRight);

                    triangles.Add(bottomRight);
                    triangles.Add(bottomLeft);
                    triangles.Add(topRight);
                }
            }
        }

        Mesh mesh = meshFilter.mesh;

        mesh.Clear();

        mesh.vertices  = vertices.ToArray();
        mesh.uv        = uvs.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.UploadMeshData(false);

        // Generate texture from pieces

        List <Texture2D> texturesToStitch = new List <Texture2D>();

        texturesToStitch.Add(_feetTextures[Random.Range(0, _feetTextures.Length)]);
        for (int i = 0; i < _bodyLength - 2; i++)
        {
            texturesToStitch.Add(_bodyTextures[Random.Range(0, _bodyTextures.Length)]);
        }
        texturesToStitch.Add(_topTextures[Random.Range(0, _topTextures.Length)]);

        int totalHeight = _bodyLength * texturesToStitch[0].height;

        int prevY = 0;

        _stitchedTexture = new Texture2D(texturesToStitch[0].width, totalHeight);
        for (int i = 0; i < texturesToStitch.Count; i++)
        {
            _stitchedTexture.SetPixels(0, prevY, texturesToStitch[i].width, texturesToStitch[i].height, texturesToStitch[i].GetPixels());
            prevY += texturesToStitch[i].height;
        }

        _stitchedTexture.Apply();
        renderer.material.SetTexture("_MainTex", _stitchedTexture);

        int colorPairIndex = Random.Range(0, _colorPairs.Length);

        renderer.material.SetColor("_FurColor", _colorPairs[colorPairIndex].furColor);
        renderer.material.SetColor("_SkinColor", _colorPairs[colorPairIndex].skinColor);

        Renderer handRenderer = FindObjectOfType <MonsterArmTag>().renderer;

        handRenderer.material.SetColor("_FurColor", _colorPairs[colorPairIndex].furColor);
        handRenderer.material.SetColor("_SkinColor", _colorPairs[colorPairIndex].skinColor);

        // Generate paths for guys to travel along
        // F**k this forever
        for (int i = 0; i < _numPathsToCreate; i++)
        {
            GameObject guyPathObj = new GameObject("GuyPath", typeof(BezierSpline));
            guyPathObj.transform.parent = transform;
            BezierSpline guyPathSpline = guyPathObj.GetComponent <BezierSpline>();

            guyPathSpline.Reset();
            for (int j = 0; j < texturesToStitch.Count - 1; j++)
            {
                guyPathSpline.AddCurve();
            }

            for (int j = 0; j < guyPathSpline.ControlPointCount; j++)
            {
                if (j == 0)
                {
                    // Set at one of the foot points
                    guyPathSpline.SetControlPoint(j, Vector3.zero + Vector3.right * _footSpawnXOffset * Mathf.Sign(Random.value - 0.5f));
                    guyPathSpline.SetControlPoint(j + 1, guyPathSpline.GetControlPoint(j) + Vector3.up);
                }
                else if (j == guyPathSpline.ControlPointCount - 1)
                {
                    // Last point
                    guyPathSpline.SetControlPoint(j, Vector3.up * _bodyScale * (appliedVerticalQuads - _verticalQuads / 2f));
                    guyPathSpline.SetControlPoint(j - 1, guyPathSpline.GetControlPoint(j) - Vector3.up);
                }
                else if (j % 3 == 0)
                {
                    guyPathSpline.SetControlPoint(j, Vector3.up * j / 3f * _verticalQuads * _bodyScale + Vector3.right * Random.Range(-_spawnXOffset, _spawnXOffset));

                    guyPathSpline.SetControlPointMode(j, BezierControlPointMode.Mirrored);
                    guyPathSpline.SetControlPoint(j + 1, guyPathSpline.GetControlPoint(j) + Vector3.up);
                }
            }
        }

        // Setup collider
        BoxCollider2D boxCollider = gameObject.AddComponent <BoxCollider2D>();

        Vector2 boxScale = boxCollider.size;

        boxScale.Scale(_boxSizeScale);

        boxCollider.size = boxScale;
    }
コード例 #31
0
 void OnEnable()
 {
     spline = (BezierSpline)target;
 }
コード例 #32
0
ファイル: EnemyTurret.cs プロジェクト: facybenbook/Starlight
    //Function called from Update to get the position where the player ship will be
    private Vector3 LeadShipPosition()
    {
        //The vec3 position that we return
        Vector3 targetPos = this.targetPlayer.transform.position;

        //Float that holds the position between our muzzle and the player ship
        float distToTarget = Vector3.Distance(this.ourWeapon.muzzleAudio.transform.position, targetPos);

        //Finding the amount of time it would take for our weapon's projectile would take to cover that distance
        //Using the formula Velocity = Distance / Time  ===>   Time = Distance / Velocity
        float projectileTime = distToTarget / this.ourWeapon.firedProjectile.forwardVelocity;

        //Now that we know about how long it will take for the projectile to reach the player's CURRENT position,
        //We need to guess how far along they will be using their current velocity

        //If the ship is in a free movement zone, we use their forward velocity
        if (this.targetPlayer.ourFreeMovement.enabled)
        {
            //Getting the direction and magnitude that the velocity is facing
            Vector3 velocityOffset = this.targetPlayer.ourRailMovement.railParentObj.ourRigidbody.velocity;
            //Multiplying the velocity
            velocityOffset = velocityOffset * projectileTime;
            //Adding the forward velocity offset to the target position
            targetPos += velocityOffset;
        }
        //If the ship is in a rail movement zone, we need to use the rail position
        else if (this.targetPlayer.ourRailMovement.enabled && this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.splineToFollow != null)
        {
            //Getting the reference to the spline that the target ship is moving on
            BezierSpline shipSpline = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.splineToFollow;

            //Getting the current amount of time that the ship has already traveled
            float currentSplineTime = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.CurrentSplineTime;
            //Getting the total time that the player will have to travel along the spline
            float totalSplineTime = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.timeToComplete;

            //Getting the speed multiplier that the player is moving at
            float speedMultiplier = this.targetPlayer.ourRailMovement.railParentObj.ourSplineMoveRB.speedMultiplier;


            //Getting the adjusted percent along the spline that the player is currently at
            float adjustedCurrentPercent = currentSplineTime / totalSplineTime;
            adjustedCurrentPercent = shipSpline.GetAdjustedPercentFromTime(adjustedCurrentPercent);

            //Getting the adjusted percent along the spline that the player is going to be at
            float adjustedTargetPercent = projectileTime * (speedMultiplier);
            adjustedTargetPercent += currentSplineTime;
            adjustedTargetPercent  = adjustedTargetPercent / totalSplineTime;
            adjustedTargetPercent  = shipSpline.GetAdjustedPercentFromTime(adjustedTargetPercent);

            //Getting the position along the spline that the ship will be at when taking into account the projectile time
            targetPos = shipSpline.GetPoint(adjustedTargetPercent);

            //Finding the offset that the player ship is from the rail center
            Vector3 currentOffset = this.targetPlayer.transform.InverseTransformPoint(shipSpline.GetPoint(adjustedCurrentPercent));

            currentOffset = new Vector3(-currentOffset.x, -currentOffset.y, -currentOffset.z);

            //Adding the offset that the player ship is from the target position
            targetPos += shipSpline.GetQuaternionAtPercent(adjustedTargetPercent) * currentOffset;
        }

        //Returning our target pos
        return(targetPos);
    }
コード例 #33
0
ファイル: SplineTracer.cs プロジェクト: Broghain/GTO7
 public void SetTrack(BezierSpline track, float t, bool reverse)
 {
     this.track = track;
     this.t = t;
 }
コード例 #34
0
ファイル: Swarmspawner.cs プロジェクト: Broghain/GTO7
 // Use this for initialization
 void Start()
 {
     spline = GetComponent<BezierSpline>();
 }
コード例 #35
0
ファイル: TestTrackSpline.cs プロジェクト: mANDROID99/IaS
 private void AssertSplinePt(BezierSpline.BezierPoint pt, Vector3 expectedStartPos, Vector3 expectedEndPos, Vector3? expectedAnchor1 = null, Vector3? expectedAnchor2 = null)
 {
     Assert.That(pt.startPos, Is.EqualTo(expectedStartPos));
     Assert.That(pt.endPos, Is.EqualTo(expectedEndPos));
     if (expectedAnchor1 != null)
     {
         Assert.That(pt.anchor1, Is.EqualTo(expectedAnchor1));
     }
     if (expectedAnchor2 != null)
     {
         Assert.That(pt.anchor2, Is.EqualTo(expectedAnchor2));
     }
 }
コード例 #36
0
    // Use this for initialization
    void Start()
    {
        t = 0;
        currentSpline = startingSpline;

        transform.position = currentSpline.GetPoint(t);
        transform.rotation = currentSpline.GetOrientation(t, Vector3.Lerp(currentSpline.startNode.transform.up, currentSpline.endNode.transform.up, t));

        lastForward = transform.forward;
    }
コード例 #37
0
    void ChangeToNextSpline()
    {
        TrackElement currentCurve = currentSpline.curve;

        if (currentSpline.curve.GetType() == typeof(Curve))
        {// If we are in a Curve
            int currentSplineIndex = currentCurve.splines.IndexOf(currentSpline);

            if (!reverse)
            {
                // If there are more splines in the current curve, change to next
                if (currentSplineIndex + 1 <= currentCurve.splines.Count - 1)
                {
                    currentSpline = currentCurve.splines[currentSplineIndex + 1];
                    t = t - 1;
                    return;
                }
                else
                { // Jump to next TrackElement

                    if (((Curve)currentCurve).nextCurve.GetType() == typeof(Curve))
                    {// Jump from curve to curve
                        Curve nextCurve = (Curve)((Curve)currentCurve).nextCurve;
                        if (nextCurve.nextCurve == currentCurve)
                        {// --->/<---
                            currentSpline = nextCurve.splines[nextCurve.splines.Count - 1];
                            reverse = true;
                            // Update t
                            t = 1 - (t - 1);
                        }
                        else if (nextCurve.previousCurve == currentCurve)
                        {// --->/--->
                            currentSpline = nextCurve.splines[0];
                            reverse = false;
                            // Update t
                            t = t - 1;
                        }
                    }

                    if (((Curve)currentCurve).nextCurve.GetType() == typeof(Bifurcation))
                    {// Jump from curve to bifurcation.
                        Bifurcation nextBifurcation = (Bifurcation)((Curve)currentCurve).nextCurve;

                        if (nextBifurcation.nextCurveRight == currentCurve)
                        {// --->/---> (From Right path to Start)
                            currentSpline = nextBifurcation.splines[0];
                            reverse = true;
                            // Update t
                            t = 1 - (t - 1);
                        }
                        else if (nextBifurcation.nextCurveLeft == currentCurve)
                        {// --->/---> (From Left path to Start)
                            currentSpline = nextBifurcation.splines[1];
                            reverse = true;
                            // Update t
                            t = 1 - (t - 1);
                        }

                        // Here we are sure that we are entering the bifurcation from the start node.
                        else if (nextBifurcation.splines[0].isPath)
                        {// --->/---> (From Start to Right path)
                            currentSpline = nextBifurcation.splines[0];
                            reverse = false;
                            // Update t
                            t = t - 1;
                        }
                        else if (nextBifurcation.splines[1].isPath)
                        {// --->\---> (From Start to Left path)
                            currentSpline = nextBifurcation.splines[1];
                            reverse = false;
                            // Update t
                            t = t - 1;
                        }
                    }

                }
            }
            else // reverse mode
            {
                // If there are more splines in the current curve, change to previous spline
                if (currentSplineIndex - 1 >= 0)
                {
                    currentSpline = currentCurve.splines[currentSplineIndex - 1];
                    t = 1 + t;
                    return;
                }
                else
                { // Jump to next TrackElement

                    if (((Curve)currentCurve).previousCurve.GetType() == typeof(Curve))
                    {// Jump to curve
                        Curve previousCurve = (Curve)((Curve)currentCurve).previousCurve;
                        if (previousCurve.nextCurve == currentCurve)
                        {// <---/<---
                            currentSpline = previousCurve.splines[((Curve)currentCurve).previousCurve.splines.Count - 1];
                            reverse = true;
                            // Update t
                            t = t + 1;
                        }
                        else if (previousCurve.previousCurve == currentCurve)
                        {// <---/--->
                            currentSpline = previousCurve.splines[0];
                            reverse = false;
                            // Update t
                            t = 1 - (t + 1);
                        }

                    }
                    if (((Curve)currentCurve).previousCurve.GetType() == typeof(Bifurcation))
                    {// Jump from curve to bifurcation.
                        Bifurcation nextBifurcation = (Bifurcation)(((Curve)currentCurve).previousCurve);

                        if (nextBifurcation.nextCurveRight == currentCurve)
                        {// --->/---> (From Right path to Start)
                            currentSpline = nextBifurcation.splines[0];
                            reverse = true;
                            // Update t
                            t = 1 + t;
                        }
                        else if (nextBifurcation.nextCurveLeft == currentCurve)
                        {// --->\---> (From Left path to Start)
                            currentSpline = nextBifurcation.splines[1];
                            reverse = true;
                            // Update t
                            t = 1 + t;
                        }
                        else if (nextBifurcation.previousCurve == currentCurve)
                        {// --->\---> (From Start to..)
                            if (nextBifurcation.splines[0].isPath)
                            {// --->/---> (From Start to Right path)
                                currentSpline = nextBifurcation.splines[0];
                                reverse = false;
                                // Update t
                                t = 1 - (1 - t);
                            }
                            else if (nextBifurcation.splines[1].isPath)
                            {// --->\---> (From Start to Left path)
                                currentSpline = nextBifurcation.splines[1];
                                reverse = false;
                                // Update t
                                t = 1 - (1 - t);
                            }
                        }
                    }

                }
            }
        }
        else if(currentSpline.curve.GetType() == typeof(Bifurcation))
        {// If we are in a Bifurcation
            Bifurcation bifurcation = (Bifurcation)currentSpline.curve;
            if (!reverse)
            {
                // Start to Right
                if (currentSpline == bifurcation.splines[0] && bifurcation.nextCurveRight.previousCurve == bifurcation)
                {// Start to Straight Right
                    if (bifurcation.nextCurveRight.GetType() == typeof(Bifurcation))
                    {// bifurcation to bifurcation
                        Bifurcation nextBifurcation = (Bifurcation)(bifurcation.nextCurveRight);
                        if (nextBifurcation.splines[0].isPath) currentSpline = nextBifurcation.splines[0];
                        else if (nextBifurcation.splines[1].isPath) currentSpline = nextBifurcation.splines[1];

                        reverse = false;
                        // Update t
                        t = t - 1;
                    }
                    else
                    {// bifurcation to Straight curve
                        currentSpline = bifurcation.nextCurveRight.splines[0];
                        reverse = false;
                        // Update t
                        t = t - 1;
                    }
                }
                else if (currentSpline == bifurcation.splines[0])
                {// Start to Reverse Curve
                    currentSpline = bifurcation.nextCurveRight.splines[bifurcation.nextCurveRight.splines.Count - 1];
                    reverse = true;
                    // Update t
                    t = 1 - (1 - t);
                }

                // Start to Left
                if (currentSpline == bifurcation.splines[1] && bifurcation.nextCurveLeft.previousCurve == bifurcation)
                {// Start to Straight Left
                    if (bifurcation.nextCurveLeft.GetType() == typeof(Bifurcation))
                    {// bifurcation to bifurcation
                        Bifurcation nextBifurcation = (Bifurcation)(bifurcation.nextCurveLeft);
                        if (nextBifurcation.splines[0].isPath) currentSpline = nextBifurcation.splines[0];
                        else if (nextBifurcation.splines[1].isPath) currentSpline = nextBifurcation.splines[1];

                        reverse = false;
                        // Update t
                        t = t - 1;
                    }
                    else
                    {// bifurcation to Straight curve
                        currentSpline = bifurcation.nextCurveLeft.splines[0];
                        reverse = false;
                        // Update t
                        t = t - 1;
                    }
                }
                else if (currentSpline == bifurcation.splines[1])
                {// Start to Reverse Curve
                    currentSpline = bifurcation.nextCurveLeft.splines[bifurcation.nextCurveLeft.splines.Count - 1];
                    reverse = true;
                    // Update t
                    t = 1 - (1 - t);
                }
            }
            else
            {// Reverse mode
                if (bifurcation.previousCurve.GetType() == typeof(Bifurcation))
                {// back to another bifurcation
                    Bifurcation previousBif = (Bifurcation)bifurcation.previousCurve;
                    if (previousBif.nextCurveRight == bifurcation) currentSpline = previousBif.splines[0];
                    if (previousBif.nextCurveLeft == bifurcation) currentSpline = previousBif.splines[1];

                    reverse = true;
                    t = t + 1;
                }
                else
                {// back to a Curve
                    currentSpline = bifurcation.previousCurve.splines[bifurcation.previousCurve.splines.Count-1];
                    reverse = true;
                    t = t + 1;
                }
            }
        }

        return;
    }
コード例 #38
0
    void SetOrder()
    {
        lastHead = 0;

        splineNumber = 0;
        for (int i = 1; i < segments.Length-1; i++) {
        //			spline = segments [current].GetComponent<RailComponent> ().rail;
            spline = segments[i].GetComponent<RailComponent>().rail;
        //			Debug.Log (spline);
            segments[i].GetComponent<RailComponent>().railNumber = splineNumber;
            if(segments[i+1].GetComponent<RailComponent>().rail == segments[i].GetComponent<RailComponent>().rail){
                segments[i].GetComponent<RailComponent>().next = segments[i+1].GetComponent<RailComponent>().transform;
            } else {
                segments[i].GetComponent<RailComponent>().tail = true;
                segments[i].GetComponent<RailComponent>().GetComponent<Collider>().enabled = false;
                lastTail = i;
        //				tails[splineNumber] = i;
                splineNumber++;
        //				Debug.Log(spline.Loop);
                if(spline.Loop){
                    Debug.Log("Loop me!");
                    segments[i].GetComponent<RailComponent>().next = segments[lastHead].GetComponent<RailComponent>().transform;
                    segments[lastHead].GetComponent<RailComponent>().last = segments[i].GetComponent<RailComponent>().transform;
                }
                segments[i+1].GetComponent<RailComponent>().head = true;
                segments[i+1].GetComponent<RailComponent>().GetComponent<Collider>().enabled = false;
                lastHead = i+1;
        //				Debug.Log("LH: "+lastHead);
        //				heads[splineNumber] = i+1;

            }
            if(segments[i-1].GetComponent<RailComponent>().rail == segments[i].GetComponent<RailComponent>().rail){
                segments[i].GetComponent<RailComponent>().last = segments[i-1].GetComponent<RailComponent>().transform;
            }

        }

        segments[0].GetComponent<RailComponent>().next = segments[1].GetComponent<RailComponent>().transform;
        segments[0].GetComponent<RailComponent>().head = true;
        segments[0].GetComponent<RailComponent>().GetComponent<Collider>().enabled = false;
        segments [0].GetComponent<RailComponent> ().railNumber = 0;
        segments[segments.Length-1].GetComponent<RailComponent>().tail = true;
        segments[segments.Length-1].GetComponent<RailComponent>().GetComponent<Collider>().enabled = false;
        segments[segments.Length-1].GetComponent<RailComponent>().last = segments[segments.Length - 2].GetComponent<RailComponent>().transform;
        segments[segments.Length-1].GetComponent<RailComponent>().railNumber = splineNumber;
        spline = segments [segments.Length - 1].GetComponent<RailComponent> ().rail;
        if (spline.Loop) {
            segments[segments.Length - 1].GetComponent<RailComponent>().next = segments[lastHead].GetComponent<RailComponent>().transform;
            segments[lastHead].GetComponent<RailComponent>().last = segments[segments.Length - 1].GetComponent<RailComponent>().transform;
        }
        //		Debug.Log (segments [segments.Length - 1].GetComponent<RailComponent> ().next);
        //		segments[0].GetComponent<RailComponent>().last = segments[segments.Length].GetComponent<RailComponent>().transform;
    }
コード例 #39
0
    void Update()
    {
        if (applicationExiting)
        {
            return;
        }

        if (cameraTexture == null || predictionTexture == null || carController == null)
        {
            return;
        }

        ogmaneo.Vec2i pixelPos = new Vec2i();

        // Remember currently active render texture
        RenderTexture currentActiveRT = RenderTexture.active;

        // Transfer the camera capture into the prediction texture (temporarily)
        RenderTexture.active = cameraTexture;
        predictionTexture.ReadPixels(new Rect(0, 0, _inputWidth, _inputHeight), 0, 0);
        predictionTexture.Apply();

        // Restore active render texture
        RenderTexture.active = currentActiveRT;

        // Transfer the RGB camera texture into ValueField2D fields
        Color actualPixel = new Color();
        Color yuvPixel    = new Color(0.0f, 0.0f, 0.0f);

        for (int x = 0; x < _inputWidth; x++)
        {
            for (int y = 0; y < _inputHeight; y++)
            {
                actualPixel = predictionTexture.GetPixel(x, y);

                // SDTV (BT.601) Y'UV conversion
                yuvPixel.r = actualPixel.r * 0.299f + actualPixel.g * 0.587f + actualPixel.b * 0.114f;   // Y' luma component

                // Chrominance
                // U = r * -0.14713 + g * -0.28886 + b * 0.436
                //yuvPixel.g = 0.0f;
                // V = r * 0.615 + g * -0.51499 + b * -0.10001
                //yuvPixel.b = 0.0f;

                predictionTexture.SetPixel(x, y, yuvPixel);
            }
        }

        // Edge Detection Convolution methods:
        //   Laplacian of the Gaussian (LoG) - https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian
        // - Sobel-Feldman and Sharr operators - https://en.wikipedia.org/wiki/Sobel_operator
        // - Prewitt operator - https://en.wikipedia.org/wiki/Prewitt_operator
        //   Kirch operator - https://en.wikipedia.org/wiki/Kirsch_operator
        Texture2D horzTexture = ConvolutionFilter.Apply(predictionTexture, ConvolutionFilter.Sobel3x3Horizontal); // ConvolutionFilter.Prewitt3x3Horizontal);
        Texture2D vertTexture = ConvolutionFilter.Apply(predictionTexture, ConvolutionFilter.Sobel3x3Vertical);   // ConvolutionFilter.Prewitt3x3Vertical);

        Texture2D convolvedTexture = new Texture2D(_inputWidth, _inputHeight, predictionTexture.format, false);
        Color     tempPixel        = new Color(0.0f, 0.0f, 0.0f);

        for (int x = 0; x < _inputWidth; x++)
        {
            for (int y = 0; y < _inputHeight; y++)
            {
                Color horzPixel = horzTexture.GetPixel(x, y);
                Color vertPixel = vertTexture.GetPixel(x, y);

                tempPixel.r = Mathf.Sqrt((horzPixel.r * horzPixel.r) + (vertPixel.r * vertPixel.r));
                tempPixel.g = tempPixel.r; // Mathf.Sqrt((horzPixel.g * horzPixel.g) + (vertPixel.g * vertPixel.g));
                tempPixel.b = tempPixel.r; // Mathf.Sqrt((horzPixel.b * horzPixel.b) + (vertPixel.b * vertPixel.b));

                convolvedTexture.SetPixel(x, y, tempPixel);
            }
        }

        predictionTexture.SetPixels(convolvedTexture.GetPixels());
        predictionTexture.Apply();

        // Transfer the RGB camera texture into ValueField2D fields
        for (int x = 0; x < _inputWidth; x++)
        {
            for (int y = 0; y < _inputHeight; y++)
            {
                actualPixel = predictionTexture.GetPixel(x, y);

                pixelPos.x = x;
                pixelPos.y = y;

                _inputField.setValue(pixelPos, actualPixel.r);

                previousImage[x, y] = sourceImage[x, y];
                sourceImage[x, y]   = actualPixel.r;// * 0.299f + actualPixel.g * 0.587f + actualPixel.b * 0.114f;
            }
        }

        // Encode scalar values from the car controller
        Steer = carController.CurrentSteerAngle / carController.m_MaximumSteerAngle;
        Accel = carController.AccelInput;
        Brake = carController.BrakeInput;

        pixelPos.x = 0;
        pixelPos.y = 0;
        _inputValues.setValue(pixelPos, Steer);

        // Setup the hierarchy input vector
        vectorvf inputVector = new vectorvf();

        inputVector.Add(_inputField);
        inputVector.Add(_inputValues);

        // Step the hierarchy
        _hierarchy.activate(inputVector);

        if (Training)
        {
            _hierarchy.learn(inputVector);
        }

        // Grab the predictions vector
        vectorvf prediction = _hierarchy.getPredictions();

        // Transfer the ValueField2D fields into the RGB prediction texture
        Color predictedPixel = new Color();

        for (int x = 0; x < _inputWidth; x++)
        {
            for (int y = 0; y < _inputHeight; y++)
            {
                pixelPos.x = x;
                pixelPos.y = y;

                predictedPixel.r = prediction[0].getValue(pixelPos);
                predictedPixel.g = predictedPixel.r; // prediction[1].getValue(pixelPos);
                predictedPixel.b = predictedPixel.r; // prediction[2].getValue(pixelPos);

                predictionTexture.SetPixel(x, y, predictedPixel);

                predictedImage[x, y] = predictedPixel.r;// * 0.299f + predictedPixel.g * 0.587f + predictedPixel.b * 0.114f;
            }
        }
        predictionTexture.Apply();

        // Wait for physics to settle
        if (_time < 1.0f)
        {
            _time += Time.deltaTime;

            // Apply hand brake
            carSteer  = 0.0f;
            carAccel  = 0.0f;
            carBrake  = -1.0f;
            HandBrake = 1.0f;
        }
        else
        {
            // Release hand brake
            HandBrake = 0.0f;

            Accel = -1.0f;
            Brake = Accel;

            pixelPos.x = 0;
            pixelPos.y = 0;

            // Update the car controller
            PredictedSteer = prediction[1].getValue(pixelPos);
            PredictedAccel = Accel;
            PredictedBrake = Brake;

            carSteer = PredictedSteer;// * carController.m_MaximumSteerAngle;
            carAccel = PredictedAccel;
            carBrake = PredictedBrake;

            // Search along the spline for the closest point to the current car position
            float   bestT = 0.0f, minDistance = 100000.0f;
            Vector3 carPosition = carController.gameObject.transform.localPosition;

            // When not training use the track spline
            BezierSpline spline = trackSpline;

            if (Training)
            {
                spline = splineList[SplineIndex];
            }

            float totalDistance = 0.0f;

            for (float t = 0.0f; t <= 1.0f; t += 0.001f)
            {
                Vector3 position     = spline.GetPoint(t);
                Vector3 positionPrev = spline.GetPoint(t - 0.001f);

                float distance = Vector3.Distance(position, carPosition);

                totalDistance += Vector3.Distance(position, positionPrev);

                if (distance <= minDistance)
                {
                    minDistance = distance;
                    bestT       = t;
                }
            }

            // Reset car position and direction?
            if (Input.GetKeyUp(KeyCode.R) || carController.Collided)
            {
                if (ForcePredictionMode == false)
                {
                    Training = true;
                }

                carController.ResetCollided();

                // Spline 0 is usually set as the spline used to create the track
                SplineIndex = 0;

                Vector3 position = spline.GetPoint(bestT);
                carController.gameObject.transform.localPosition = position;

                Vector3 splineDirection = spline.GetDirection(bestT).normalized;
                carController.gameObject.transform.forward = -splineDirection;
            }

            // Determine the difference between the input image (t) and predicted image (t+1)
            CalculateNormalizedCrossCorrelation();

            // Toggle training on iff too divergent?
            if (Training == false && ForcePredictionMode == false && NCC < 0.25f)
            {
                Training = true;
            }

            // Toggle training off iff quite confident?
            if (Training == true && NCC > 0.85f && LapCount >= initialTrainingLaps)
            {
                Training = false;
            }

            if (carController.CurrentSpeed < 2.0f)
            {
                Training = true;
            }

            if (Training)
            {
                _trainingCount++;
            }
            else
            {
                _predictingCount++;
            }

            if (Training && spline != null)
            {
                Vector3 carDirection = -carController.gameObject.transform.forward.normalized;

                Vector3 targetPosition = spline.GetPoint(bestT + SteerAhead / totalDistance);

                //Vector3 splineDirection = spline.GetDirection(bestT).normalized;

                Vector3 targetDirection = (targetPosition - carPosition).normalized;

                float angle = (1.0f - Vector3.Dot(carDirection, targetDirection));// * Mathf.Rad2Deg;

                Vector3 right  = Vector3.Cross(carDirection, Vector3.up);
                float   angle2 = Vector3.Dot(right, targetDirection);

                float newCarSteer = Mathf.Exp(256.0f * angle) - 1.0f;

                if (Mathf.Abs(minDistance) > 0.01f)//newCarSteer > Mathf.PI / 64.0f)
                {
                    newCarSteer += angle2 * Mathf.Abs(minDistance);
                }

                if (angle2 > 0.0f)
                {
                    newCarSteer = -newCarSteer;
                }

                if (newCarSteer > 1.0f)
                {
                    newCarSteer = 1.0f;
                }
                else
                if (newCarSteer < -1.0f)
                {
                    newCarSteer = -1.0f;
                }

                float steerBlend = 0.75f;
                carSteer = (steerBlend * newCarSteer) + ((1.0f - steerBlend) * carSteer);

                if (enableDebugLines)
                {
                    debugLinePositions[0] = carController.gameObject.transform.localPosition;
                    debugLinePositions[1] = debugLinePositions[0] + carDirection * 10.0f;
                    debugLinePositions[2] = carController.gameObject.transform.localPosition;
                    debugLinePositions[3] = debugLinePositions[2] + targetDirection * 10.0f;
                    debugLine.SetPositions(debugLinePositions);
                }
            }

            float totalCount = _trainingCount + _predictingCount;

            if (totalCount == 0.0f)
            {
                TrainingPercent   = 1.0f;
                PredictionPercent = 0.0f;
            }
            else
            {
                TrainingPercent   = (float)_trainingCount / totalCount;
                PredictionPercent = (float)_predictingCount / totalCount;
            }

            if (bestT < prevBestT)
            {
                LapCount++;

                _trainingCount   = 0;
                _predictingCount = 0;

                if ((LapCount % lapsPerSpline) == 0)
                {
                    SplineIndex++;

                    if (SplineIndex >= splineList.Length)
                    {
                        SplineIndex = 0;
                    }
                }
            }

            prevBestT = bestT;
        }

        if (userControl)
        {
            // Control overides
            // pass the input to the car!
            float h = CrossPlatformInputManager.GetAxis("Horizontal");
            float v = CrossPlatformInputManager.GetAxis("Vertical");
#if !MOBILE_INPUT
            float handbrake = CrossPlatformInputManager.GetAxis("Jump");
#endif
            carSteer  = h;
            carAccel  = v;
            carBrake  = v;
            HandBrake = handbrake;
        }

        // Toggle training?
        if (Input.GetKeyUp(KeyCode.T))
        {
            Training            = !Training;
            ForcePredictionMode = false;
        }
        else
        // Force prediction mode?
        if (Input.GetKeyUp(KeyCode.F))
        {
            Training            = false;
            ForcePredictionMode = true;
        }

        // Save out the current state of the hierarchy?
        if (Input.GetKeyUp(KeyCode.O) && hierarchyFileName.Length > 0)
        {
            _hierarchy.save(_res.getComputeSystem(), hierarchyFileName);
            print("Saved OgmaNeo hierarchy to " + hierarchyFileName);
        }
    }
コード例 #40
0
ファイル: LineSerie.cs プロジェクト: asine/Live-Charts
        private IEnumerable <Shape> _addSerieAsBezier(Point[] points, Color color, double storkeThickness,
                                                      bool animate = true)
        {
            var addedFigures = new List <Shape>();

            Point[] cp1, cp2;
            BezierSpline.GetCurveControlPoints(points, out cp1, out cp2);

            var lines     = new PathSegmentCollection();
            var areaLines = new PathSegmentCollection {
                new LineSegment(points[0], true)
            };
            var l = 0d;

            for (var i = 0; i < cp1.Length; ++i)
            {
                lines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
                areaLines.Add(new BezierSegment(cp1[i], cp2[i], points[i + 1], true));
                //it would be awesome to use a better formula to calculate bezier lenght
                l += Math.Sqrt(
                    Math.Pow(Math.Abs(cp1[i].X - cp2[i].X), 2) +
                    Math.Pow(Math.Abs(cp1[i].Y - cp2[i].Y), 2));
                l += Math.Sqrt(
                    Math.Pow(Math.Abs(cp2[i].X - points[i + 1].X), 2) +
                    Math.Pow(Math.Abs(cp2[i].Y - points[i + 1].Y), 2));
            }
            //aprox factor, it was calculated by aproximation.
            //the more line is curved, the more it fails.
            l = l * .65;
            areaLines.Add(new LineSegment(new Point(points.Max(x => x.X), ToPlotArea(_chart.Min.Y, AxisTags.Y)), true));
            var f  = new PathFigure(points[0], lines, false);
            var fa = new PathFigure(ToPlotArea(new Point(_chart.Min.X, _chart.Min.Y)), areaLines, false);
            var g  = new PathGeometry(new[] { f });
            var ga = new PathGeometry(new[] { fa });

            var path = new Path
            {
                Stroke = new SolidColorBrush {
                    Color = color
                },
                StrokeThickness    = storkeThickness,
                Data               = g,
                StrokeEndLineCap   = PenLineCap.Round,
                StrokeStartLineCap = PenLineCap.Round,
                StrokeDashOffset   = l,
                StrokeDashArray    = new DoubleCollection {
                    l, l
                },
                ClipToBounds = true
            };
            var patha = new Path
            {
                StrokeThickness = 0,
                Data            = ga,
                Fill            = new SolidColorBrush {
                    Color = color, Opacity = .05
                },
                ClipToBounds = true
            };

            _chart.Canvas.Children.Add(path);
            addedFigures.Add(path);
            if (_chart.IncludeArea)
            {
                _chart.Canvas.Children.Add(patha);
                addedFigures.Add(patha);
            }

            var draw = new DoubleAnimationUsingKeyFrames
            {
                BeginTime = TimeSpan.FromSeconds(0),
                KeyFrames = new DoubleKeyFrameCollection
                {
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(1),
                        Value   = l
                    },
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(750),
                        Value   = 0
                    }
                }
            };

            Storyboard.SetTarget(draw, path);
            Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty));
            var sbDraw = new Storyboard();

            sbDraw.Children.Add(draw);
            var animated = false;

            if (!_chart.DisableAnimation)
            {
                if (animate)
                {
                    sbDraw.Begin();
                    animated = true;
                }
            }
            if (!animated)
            {
                path.StrokeDashOffset = 0;
            }
            return(addedFigures);
        }
コード例 #41
0
    public void init(float speed, float hoverHeight, float hoverVariance, float hoverSpeed, float rotationSpeed, float startPoint, float startdistance, float endDistance, BezierSpline spline,
                     Transform boy)
    {
        this.speed         = speed;
        this.hoverHeight   = hoverHeight;
        this.hoverVariance = hoverVariance;
        this.hoverSpeed    = hoverSpeed;
        this.rotationSpeed = rotationSpeed;
        this.spline        = spline;
        this.boy           = boy;
        this.endDistance   = endDistance;

        randValue = Random.Range(0.1f, 0.9f);
        randDir   = (int)Random.Range(0f, 2f);
        randDir   = (randDir == 0) ? -1 : randDir;

        splineLength = spline.GetSplineLength();

        transform.Rotate(0, Random.Range(0, 180), 0);

        t = startdistance / splineLength + startPoint;
        t = (t > 1f) ? 1f : t;
        transform.position = spline.GetPoint(t);
    }
コード例 #42
0
ファイル: TubeWithBezier.cs プロジェクト: matheuspb95/VRRacer
 public void CreateTube()
 {
     spline = GetComponent <BezierSpline>();
     StartCoroutine(Generate());
 }
コード例 #43
0
 public override void AddVertex(Spline vertex2D)
 {
     points.Add(vertex2D);
     vertex2Ds.Clear();
     vertex2Ds = new BezierSpline(points).GenerateSpline(50);
 }
コード例 #44
0
    private void OnSceneGUI()
    {
        if (spline == null)
        {
            spline = master.spline;
        }

        handleTransform = spline.transform;

        handleRotation = Tools.pivotRotation == PivotRotation.Local ?
                         handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);

        for (int i = 1; i < spline.ControlPointCount; i += 3)
        {
            Vector3 p1 = ShowPoint(i);
            Vector3 p2 = ShowPoint(i + 1);
            Vector3 p3 = ShowPoint(i + 2);

            Handles.color = modeColors[(int)spline.GetControlPointMode(i)];
            Handles.DrawLine(p0, p1);
            Handles.color = modeColors[(int)spline.GetControlPointMode(i + 2)];
            Handles.DrawLine(p2, p3);
            Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
            p0 = p3;
        }

        /*
         * for (int i = 0; i < 1; i++)
         * {
         *  float t = (i) / (float)(master.LenghtSegmentsCount - 1);
         *
         *  Vector3 startPoint = master.transform.TransformPoint(spline.GetPoint(t));
         *  Vector3 normal = spline.GetDirection(t);
         *
         *  float A = normal.x;
         *  float B = normal.y;
         *  float C = normal.z;
         *
         *  //Vector3 scale = CreateCylinder.RotateVector(spline.GetScale(t), normal, spline.GetRotationZ(t));
         *  Vector3 scale = spline.GetScale(t);
         *  scale = new Vector3(scale.x - 1, scale.y - 1, scale.z - 1);
         *
         *
         *  for (int j = 0; j <= master.WidthSegmentsCount; j++)
         *  {
         *      float n = (j / (float)(master.WidthSegmentsCount) * 360f + spline.GetRotationZ(t)) * Mathf.Deg2Rad;
         *
         *      float x = startPoint.x + master.radius1 / Mathf.Sqrt(A * A + C * C)
         * (C * Mathf.Cos(n) - A * B * Mathf.Sin(n)
         *          / Mathf.Sqrt(A * A + B * B + C * C));
         *
         *      float y = startPoint.y + master.radius1 * Mathf.Sqrt(A * A + C * C)
         *          / Mathf.Sqrt(A * A + B * B + C * C) * Mathf.Sin(n);
         *
         *      float z = startPoint.z - master.radius1 / Mathf.Sqrt(A * A + C * C)
         * (A * Mathf.Cos(n) + B * C * Mathf.Sin(n)
         *          / Mathf.Sqrt(A * A + B * B + C * C));
         *
         *      Vector3 result = new Vector3(x, y, z);
         *
         *      Handles.color = Color.blue;
         *      Handles.DrawLine(startPoint, result);
         *
         *      Vector3 _normal = result - startPoint;
         *      _normal = _normal.normalized;
         *
         *
         *
         *      Handles.color = Color.white;
         *      Handles.DrawLine(result, result +_normal);
         *
         *      //var res = result;
         *      //Vector3 perpendicular = Vector3.Cross( normal ,_normal);
         *      Handles.color = Color.blue;
         *      //Handles.DrawLine(result, result + perpendicular);
         *      //Vector3 offset = Vector3.Project(scale, _normal);
         *
         *      Handles.color = Color.green;
         *      //Handles.DrawLine(result, result + offset);
         *
         *      Vector3  offset = new Vector3(_normal.x * scale.x, _normal.y * scale.y, _normal.z * scale.z);
         *      offset = Vector3.ProjectOnPlane(offset, normal);
         *      //offset *= scale.magnitude;
         *
         *      //result += offset * offset.magnitude;
         *
         *      Handles.color = Color.red;
         *      Handles.DrawLine(result, result  + offset);
         *
         *
         *
         *
         *      Handles.color = Color.green;
         *      //Handles.DrawLine(result, result + scale);
         *      // Debug.Log(scale.sqrMagnitude);
         *
         *      //scale = CreateCylinder.RotateVector(scale, normal, spline.GetRotationZ(t));
         *
         *      //Debug.Log(scale.sqrMagnitude);
         *
         *  }
         * }
         */
        //ShowVelocity();
    }
コード例 #45
0
    public void parsePDB()
    {
        // for determining hydrogen bonds
        List <Vector3> hBondAcceptors = new List <Vector3> ();
        List <Vector3> hBondDonors    = new List <Vector3> ();


parseMol:                                                       // iteration start if multiple input files are used

        BezierSpline[] ribbonSplineList = new BezierSpline[30]; //for drawing protein lines (30 is max number of chains)


        int numAtoms = (int)mol.NumAtoms() + 1;


        atoms = new GameObject[numAtoms];


        int maxHelix = 500;

        radius = new float[maxHelix, numAtoms];

        int ribbonChainIndex = 0;


        OBElementTable table = new OBElementTable();

        int currentChain = -1;


        OBAtom[] alphaCarbons     = new OBAtom[numAtoms / 4];
        int      alphaCarbonCount = 0;

        List <Vector3> atomPositions = new List <Vector3> ();
        List <string>  atomElements  = new List <string> ();


        for (int i = 1; i < numAtoms; i++)
        {
            OBAtom    atom = mol.GetAtom(i);
            string    tag;
            OBResidue res      = atom.GetResidue();
            Vector3   position = new Vector3((float)atom.GetX(), (float)atom.GetY(), (float)atom.GetZ());
            string    elem     = table.GetSymbol((int)atom.GetAtomicNum()).ToUpper();


            //checks for pharmacophore labels
            if (res.GetName() == "ACC" || res.GetName() == "FOB" || res.GetName() == "POS" || res.GetName() == "NEG" || res.GetName() == "RNG" || res.GetName() == "DON")
            {
                if (atom.IsHydrogen())                //added hydrogens gets the same resName and has to be ignored
                {
                    continue;
                }
                renderPharmacophore = true;
            }
            else
            {
                renderPharmacophore = false;
            }

            // pharmacophores
            if (res.GetName() == "EXC")
            {
                if (atom.IsHydrogen())                //added hydrogens gets the same resName and has to be ignored
                {
                    continue;
                }
                renderEXC           = true;
                renderPharmacophore = true;
            }
            else
            {
                renderEXC = false;
            }

            //creates the atom object
            atoms[i] = createAtomType(elem, position);

            int n;
            if (int.TryParse(res.GetName(), out n))
            {
                if (CollectionOfLigands == null)
                {
                    CollectionOfLigands = new List <List <GameObject> >();
                    CollectionOfLigands.Add(new List <GameObject>());
                }
                while (n + 1 > CollectionOfLigands.Count)
                {
                    CollectionOfLigands.Add(new List <GameObject>());
                }
                CollectionOfLigands[n].Add(atoms[i]);
            }

            if (res.GetResidueProperty(9))             //water
            {
                tag = "water";
            }
            else if (res.GetAtomProperty(atom, 4) || (atom.IsHydrogen() && !res.GetResidueProperty(5))) //ligand
            {
                if (res.GetResidueProperty(5))                                                          //ion (should be 3 but a bug in openbabel labels ions as protein, thats why the check has to be done inside the ligand check)
                {
                    tag = "ion";
                }
                else
                {
                    TextMesh lText = atoms [i].transform.Find("Text").GetComponent <TextMesh> ();
                    lText.color = textColor;
                    if (renderPharmacophore)
                    {
                        tag            = "hetatms";              //make sure pharmacophores always show
                        lText.text     = res.GetName() + ":" + res.GetIdx();
                        lText.fontSize = labelFontSize;
                    }
                    else
                    {
                        tag = "hetatmbs";
                        if (ligandText)
                        {
                            lText.text     = elem + ":" + i.ToString();
                            lText.fontSize = labelFontSize;
                        }
                    }


                    if (sphere)
                    {
                        atoms [i].transform.localScale *= 4;
                    }

                    if (atom.IsHbondAcceptor())
                    {
                        foreach (Vector3 candidatePos in hBondDonors)
                        {
                            checkHBond(candidatePos, position);
                        }
                    }

                    if (atom.IsHbondDonor())
                    {
                        foreach (Vector3 candidatePos in hBondAcceptors)
                        {
                            checkHBond(candidatePos, position);
                        }
                    }
                }
            }
            else               //protein
            {
                tag = "balls";

                atomPositions.Add(position);

                atomElements.Add(elem);

                if (atom.IsHbondAcceptor())
                {
                    hBondAcceptors.Add(position);
                }
                else
                {
                    hBondDonors.Add(position);
                }

                if (res.GetAtomProperty(atom, 0))                //alpha carbon
                {
                    alphaCarbons[alphaCarbonCount] = atom;
                    if (alphaCarbonCount > 6)                   //check if the ribbon is alpha helix using torsion angles
                    {
                        double torsion     = mol.GetTorsion(atom, alphaCarbons[alphaCarbonCount - 1], alphaCarbons[alphaCarbonCount - 2], alphaCarbons[alphaCarbonCount - 3]);
                        double prevTorsion = mol.GetTorsion(alphaCarbons[alphaCarbonCount - 4], alphaCarbons[alphaCarbonCount - 5], alphaCarbons[alphaCarbonCount - 6], alphaCarbons[alphaCarbonCount - 7]);
                        double torsionSum  = torsion + prevTorsion;
                        if (torsionSum > 99 && torsionSum < 111)
                        {
                            for (int j = ribbonChainIndex - 7; j <= ribbonChainIndex; j++)
                            {
                                radius [currentChain, j] = 1.5f;                                        //alpha helix
                            }
                        }
                        else
                        {
                            radius [currentChain, ribbonChainIndex] = 0.5f;
                        }
                    }
                    alphaCarbonCount++;


                    if (proteinText)                       //only displays text on alpha carbons
                    {
                        TextMesh pText = atoms [i].transform.Find("Text").GetComponent <TextMesh> ();
                        pText.color    = textColor;
                        pText.text     = res.GetName() + " -" + res.GetNumString();
                        pText.fontSize = labelFontSize;
                    }

                    int tempChain = (int)res.GetChainNum();
                    if (tempChain != currentChain)
                    {
                        currentChain     = tempChain;
                        ribbonChainIndex = 0;
                    }


                    //add points for ribbon rendering
                    addBezierPoint(ribbonSplineList, currentChain, ribbonChainIndex, position);



                    ribbonChainIndex++;
                }
            }

            atoms[i].transform.tag = tag;
            centerPos += position;
            centerCount++;
        }

        //createSurface (atomPositions,atomElements);
        Debug.Log(hBondAcceptors.Count + " " + hBondDonors.Count);
        //evaluate bonds
        for (int i = 0; i < mol.NumBonds(); i++)
        {
            OBBond    bond   = mol.GetBond(i);
            OBAtom    atom   = mol.GetAtom((int)bond.GetBeginAtomIdx());
            OBResidue res    = atom.GetResidue();
            bool      ligand = res.GetAtomProperty(atom, 4) || (atom.IsHydrogen() && !res.GetResidueProperty(5));
            if (ligand && sphere)            //no ligand bonds if display mode is CPK sphere
            {
                continue;
            }
            try {
                connect(atoms[bond.GetBeginAtomIdx()], atoms[bond.GetEndAtomIdx()], bond);
            } catch (System.Exception e) {
                Debug.Log(e);
            }
        }

        //handle pharmacophore vectors
        if (mol.HasData("VECTOR"))
        {
            string[] vectors = mol.GetData("VECTOR").GetValue().Split(new string[] { "\n" }, StringSplitOptions.None);
            foreach (string vector in vectors)
            {
                string[] idx = vector.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                try {
                    Vector3 pos = new Vector3(float.Parse(idx[1]), float.Parse(idx[2]), float.Parse(idx[3]));
                    int     id  = int.Parse(idx[0]);
                    drawVector(atoms[id], pos, mol.GetAtom(id).GetResidue().GetName());
                } catch (System.Exception e) {
                    Debug.Log(e);
                }
            }
        }


        //render protein ribbons
        drawRibbons(ribbonSplineList, "ribbons");          //must be before alpha due to indexing
        drawRibbons(ribbonSplineList, "alpha");

        // check for separate ligand file
        if (file.Contains("protein"))
        {
            file = file.Replace("protein", "ligand");
            string file1 = file.Replace("." + extension, ".sdf");          // .+extension incase the format would also appear in the file name
            string file2 = file.Replace("." + extension, ".mol2");
            if (File.Exists(file1))
            {
                readMol(file);
                goto parseMol;
            }
            else if (File.Exists(file2))
            {
                readMol(file);
                goto parseMol;
            }
        }

        center = createObject(new GameObject(), centerPos / centerCount);           //the center of the pdb
        show();
    }
コード例 #46
0
    public override void OnInspectorGUI()
    {
        spline = target as BezierSpline;

        EditorGUI.BeginChangeCheck();

        float lengthTimeStep = EditorGUILayout.FloatField("Length Calculation Time Step", spline.GetLengthCalculationTimeStep());

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(spline, "LengthCalculationTimeStepChange");

            spline.SetLengthCalculationTimeStep(lengthTimeStep);

            EditorUtility.SetDirty(spline);
        }

        EditorGUILayout.LabelField("Spline Length", spline.GetSplineLength().ToString());

        EditorGUI.BeginChangeCheck();

        bool loop = EditorGUILayout.Toggle("Loop Spline", spline.GetLoop());

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(spline, "ToggleLoopSpline");

            spline.SetLoop(loop);

            EditorUtility.SetDirty(spline);
        }

        bool foldoutAll = Event.current.type == EventType.MouseUp && Event.current.modifiers == EventModifiers.Alt;

        EditorGUILayout.BeginHorizontal();

        EditorGUI.BeginChangeCheck();

        bool foldoutPoints = EditorGUILayout.Foldout(spline.GetFoldout(0), "Points", true);

        if (EditorGUI.EndChangeCheck() && foldoutAll)
        {
            spline.SetAllFoldouts(foldoutPoints);
        }

        GUIStyle buttonStyle = new GUIStyle(GUI.skin.button)
        {
            fixedWidth    = 20,
            fixedHeight   = 20,
            fontStyle     = FontStyle.Bold,
            fontSize      = 20,
            clipping      = TextClipping.Overflow,
            contentOffset = new Vector2(1, -1)
        };

        DrawAddButton(-1, buttonStyle);

        EditorGUILayout.EndHorizontal();

        if (foldoutPoints)
        {
            EditorGUI.indentLevel++;

            for (int i = 0; i < spline.GetPointCount(); i += 3)
            {
                if (i != spline.GetPointCount() - 1 || !loop)
                {
                    EditorGUILayout.BeginHorizontal();

                    int foldoutNumber = (i / 3) + 1;

                    bool foldoutPoint = EditorGUILayout.Foldout(spline.GetFoldout(foldoutNumber), "Point " + foldoutNumber, true);

                    if (spline.GetPointCount() > 4 && (!loop || spline.GetPointCount() > 7))
                    {
                        if (GUILayout.Button("-", buttonStyle))
                        {
                            Undo.RecordObject(spline, "RemoveSplineCurve");

                            spline.RemovePoint(i);

                            EditorUtility.SetDirty(spline);

                            break;
                        }
                    }

                    DrawAddButton(i, buttonStyle);

                    EditorGUILayout.EndHorizontal();

                    if (foldoutPoint)
                    {
                        EditorGUI.indentLevel++;

                        DrawPointPositionField(i, "Local Position");

                        if (i == 0)
                        {
                            if (loop)
                            {
                                DrawPointPositionField(i + 1, "Handle 1");

                                DrawPointPositionField(spline.GetPointCount() - 2, "Handle 2");
                            }
                            else
                            {
                                DrawPointPositionField(i + 1, "Handle");
                            }
                        }
                        else if (i == spline.GetPointCount() - 1)
                        {
                            DrawPointPositionField(i - 1, "Handle");
                        }
                        else
                        {
                            DrawPointPositionField(i - 1, "Handle 1");

                            DrawPointPositionField(i + 1, "Handle 2");
                        }

                        DrawPointModeField(i, "Mode");

                        EditorGUI.indentLevel--;
                    }

                    spline.SetFoldout(foldoutNumber, foldoutPoint);
                }
            }

            EditorGUI.indentLevel--;
        }

        spline.SetFoldout(0, foldoutPoints);

        if (selectedIndex >= 0 && selectedIndex < spline.GetPointCount())
        {
            GUILayout.Label("Selected Point", EditorStyles.boldLabel);

            EditorGUI.indentLevel++;

            EditorGUI.BeginChangeCheck();

            DrawPointPositionField(selectedIndex, "Local Position");

            DrawPointModeField(selectedIndex, "Mode");
        }
    }
コード例 #47
0
 public ColorSpline()
 {
     spline = new BezierSpline();
 }
コード例 #48
0
ファイル: PieceView.cs プロジェクト: dshook/centauri-tac
 public void Init()
 {
     moveSpline = GameObject.Find("PieceMoveSpline").GetComponent<BezierSpline>();
 }
コード例 #49
0
    void ReallocateNodeOverSpline(Transform node, BezierSpline spline, int depth)
    {
        float newPosition;

        // Collide with spline that can belong to 2 possible objects, biffurcation or curve
        Curve curve = spline.transform.parent.GetComponent<Curve>();
        Bifurcation bifurcation = spline.transform.parent.GetComponent<Bifurcation>();

        if (curve != null)
        {// we are in a curve
            Debug.DrawLine(transform.position, nodeToFollow.position, Color.cyan);
        }

        if (bifurcation != null)
        {// we are in a bifurcation

            if (bifurcation.splines[0].isPath) spline = bifurcation.splines[0];
            else spline = bifurcation.splines[1];
        }

        newPosition = spline.GetClosestPoint(transform.position + transform.forward * distToNode, 0.01f);
        nodeToFollow.position = spline.GetPoint(newPosition);
        nodeToFollow.rotation = spline.GetOrientation(newPosition, transform.up);

        // end or beggining of spline reached, check next/previous spline
        if (newPosition == 2)
        {// jump to previous spline

            if (depth == 1)
            {// avoid infinite recursive loops
                nodeToFollow.position = spline.startNode.transform.position;
                nodeToFollow.rotation = spline.startNode.transform.rotation;
                return;
            }

            RaycastHit hit;

            Vector3 dir = -spline.startNode.transform.forward;
            //if (spline.startNode.reverse == true) dir *= -1;

            if (Physics.Raycast(spline.startNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30))
            {
                spline = hit.collider.transform.GetComponent<BezierSpline>();
            }
            ReallocateNodeOverSpline(nodeToFollow, spline, 1);
        }
        if (newPosition == 3)
        {// jump to next spline

            if (depth == 1)
            {// avoid infinite recursive loops
                nodeToFollow.position = spline.endNode.transform.position;
                nodeToFollow.rotation = spline.endNode.transform.rotation;
                return;
            }

            RaycastHit hit;

            Vector3 dir = spline.endNode.transform.forward;
            //if (spline.endNode.reverse == true)
            //    dir *= -1;

            if (Physics.Raycast(spline.endNode.position + dir + new Vector3(0, 2, 0), -transform.up, out hit, 30))
            {
                spline = hit.collider.transform.GetComponent<BezierSpline>();
            }

            ReallocateNodeOverSpline(nodeToFollow, spline, 1);
        }
    }
コード例 #50
0
 public void SplitPath(BezierSpline spline)
 {
     Array.Resize(ref bezierSplines, bezierSplines.Length + 1);
     createNewBezierSpline(bezierSplines.Length - 1, spline.Points[spline.Points.Length - 1]);
     spline.addConnectionTospline(bezierSplines[bezierSplines.Length - 1]);
 }
コード例 #51
0
ファイル: GF47CameraPathEditor.cs プロジェクト: GF47/GRT
        // 画点,返回值为是否刷新检视面板
        private static bool DrawPoint(BezierSpline bs, int index, ref int selectedIndex)
        {
            if (bs.points == null || bs.Count < 1)
            {
                return(false);
            }

            bool refreshInspector = false;

            BezierPoint point = bs[index];

            float size = HandleUtility.GetHandleSize(point.Position);

            Handles.color = Color.blue;
            if (Handles.Button(point.Position, Quaternion.identity, size * HANDLE_SIZE, size * PICK_SIZE, Handles.DotHandleCap))
            {
                selectedIndex    = index;
                refreshInspector = true;
            }

            if (_showHandles)
            {
                Handles.color = Color.gray;
                if (Handles.Button(point.HandleL, Quaternion.identity, size * HANDLE_SIZE, size * PICK_SIZE, Handles.DotHandleCap) || Handles.Button(point.HandleR, Quaternion.identity, size * HANDLE_SIZE, size * PICK_SIZE, Handles.DotHandleCap))
                {
                    selectedIndex    = index;
                    refreshInspector = true;
                }
            }

            if (selectedIndex == index)
            {
                Vector3 p  = point.Position;
                Vector3 pl = point.HandleL;
                Vector3 pr = point.HandleR;

                p = Handles.PositionHandle(p, Quaternion.identity);
                if (_showHandles)
                {
                    pl = Handles.PositionHandle(pl, Quaternion.identity);
                    pr = Handles.PositionHandle(pr, Quaternion.identity);
                }

                if (p != point.Position)
                {
                    Undo.RecordObject(bs, "change pos");
                    point.Position = p;
                    EditorUtility.SetDirty(bs);
                    refreshInspector = true;
                }
                else if (pl != point.HandleL)
                {
                    Undo.RecordObject(bs, "change left handler");
                    point.HandleL = pl;
                    EditorUtility.SetDirty(bs);
                    refreshInspector = true;
                }
                else if (pr != point.HandleR)
                {
                    Undo.RecordObject(bs, "change right handler");
                    point.HandleR = pr;
                    EditorUtility.SetDirty(bs);
                    refreshInspector = true;
                }
            }
            if (_showHandles)
            {
                Handles.DrawLine(point.Position, point.HandleL);
                Handles.DrawLine(point.Position, point.HandleR);
            }
            return(refreshInspector);
        }
コード例 #52
0
ファイル: CustomerAutoPilot.cs プロジェクト: lucbarr/pls
 void Start()
 {
     spline = GameObject.FindWithTag("CustomerQueue").GetComponent <BezierSpline>();
 }
コード例 #53
0
ファイル: GF47CameraPathEditor.cs プロジェクト: GF47/GRT
        private void OnGUI()
        {
            bool refreshSv = false;

            EditorGUILayout.BeginHorizontal();
            BezierSpline tmpBs = (BezierSpline)EditorGUILayout.ObjectField("相机路径", _cameraBSpline, typeof(BezierSpline), false);

            if (_cameraBSpline != tmpBs)
            {
                _cameraBSpline = tmpBs;
                refreshSv      = true;
            }
            tmpBs = (BezierSpline)EditorGUILayout.ObjectField("焦点路径", _targetBSpline, typeof(BezierSpline), false);
            if (_targetBSpline != tmpBs)
            {
                _targetBSpline = tmpBs;
                refreshSv      = true;
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(10f);

            _scrollViewPos = EditorGUILayout.BeginScrollView(_scrollViewPos, false, false);

            int insertID_C = -1; int insertID_T = -1;
            int removeID_C = -1; int removeID_T = -1;

            int rowCount = -1;

            if (_cameraBSpline != null)
            {
                rowCount = _cameraBSpline.Count;
            }
            if (_targetBSpline != null)
            {
                rowCount = Mathf.Max(rowCount, _targetBSpline.Count);
            }
            for (int i = 0; i < rowCount; i++)
            {
                EditorGUILayout.BeginHorizontal();

                // 相机贝塞尔点
                refreshSv |= DrawBezierPointInspector(_cameraBSpline, i, ref insertID_C, ref removeID_C, ref _cameraSelectedID);

                // 焦点贝塞尔点
                refreshSv |= DrawBezierPointInspector(_targetBSpline, i, ref insertID_T, ref removeID_T, ref _targetSelectedID);

                EditorGUILayout.EndHorizontal();
                GUILayout.Space(10f);
            }
            EditorGUILayout.EndScrollView();

            if (_cameraBSpline != null)
            {
                if (insertID_C > -1)
                {
                    Point p = _cameraBSpline.GetResult((insertID_C - 0.5f) / (_cameraBSpline.Count - 1));
                    Undo.RecordObject(_cameraBSpline, "insert bezier point");
                    Vector3 pp = p.position;
                    Vector3 pn = p.velocity.normalized;
                    _cameraBSpline.Insert(insertID_C, new BezierPoint(pp, pp - pn, pp + pn, BezierPoint.PointType.Smooth));
                    EditorUtility.SetDirty(_cameraBSpline);
                }
                if (removeID_C > -1)
                {
                    Undo.RecordObject(_cameraBSpline, "remove bezier point");
                    _cameraBSpline.RemoveAt(removeID_C);
                    EditorUtility.SetDirty(_cameraBSpline);
                }
            }
            if (_targetBSpline != null)
            {
                if (insertID_T > -1)
                {
                    Point p = _targetBSpline.GetResult((insertID_T - 0.5f) / (_targetBSpline.Count - 1));
                    Undo.RecordObject(_targetBSpline, "insert bezier point");
                    Vector3 pp = p.position;
                    Vector3 pn = p.velocity.normalized;
                    _targetBSpline.Insert(insertID_T, new BezierPoint(pp, pp - pn, pp + pn, BezierPoint.PointType.Smooth));
                    EditorUtility.SetDirty(_targetBSpline);
                }
                if (removeID_T > -1)
                {
                    Undo.RecordObject(_targetBSpline, "remove bezier point");
                    _targetBSpline.RemoveAt(removeID_T);
                    EditorUtility.SetDirty(_targetBSpline);
                }
            }

            EditorGUILayout.BeginHorizontal();

            if (_cameraBSpline != null)
            {
                if (GUILayout.Button("Add", EditorStyles.miniButtonLeft, GUILayout.MinWidth(20f)))
                {
                    Undo.RecordObject(_cameraBSpline, "add bezier point");
                    _cameraBSpline.Insert(_cameraBSpline.Count, new BezierPoint(GetSceneView().camera.transform.position));
                    EditorUtility.SetDirty(_cameraBSpline);
                    refreshSv = true;
                }

                if (GUILayout.Button("Set", EditorStyles.miniButtonMid, GUILayout.MinWidth(20f)))
                {
                    if (_cameraSelectedID > -1)
                    {
                        Undo.RecordObject(_cameraBSpline, "change pos");
                        _cameraBSpline[_cameraSelectedID].Position = GetSceneView().camera.transform.position;
                        EditorUtility.SetDirty(_cameraBSpline);
                        refreshSv = true;
                    }
                }

                if (GUILayout.Button("Set SceneView", EditorStyles.miniButtonRight, GUILayout.MinWidth(20f)))
                {
                    if (_cameraSelectedID > -1)
                    {
                        SceneView sv = GetSceneView();
                        sv.FixNegativeSize();
                        Vector3    pivot      = sv.pivot;
                        Vector3    pos        = pivot;
                        Quaternion quaternion = Quaternion.LookRotation(pivot - _cameraBSpline[_cameraSelectedID].Position);

                        #region  要打开

                        MethodInfo mf = typeof(SceneView).GetMethod("CalcCameraDist", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                        if (mf != null)
                        {
                            pos -= (quaternion * Vector3.forward).normalized * (float)mf.Invoke(sv, null);// 这个位置一直不对
                        }

                        #endregion  要打开

                        sv.LookAtDirect(pos, quaternion);
                        sv.pivot = pivot;
                    }
                }
            }
            if (_targetBSpline != null)
            {
                if (GUILayout.Button("Add", EditorStyles.miniButtonLeft, GUILayout.MinWidth(20f)))
                {
                    Undo.RecordObject(_targetBSpline, "add bezier point");
                    _targetBSpline.Insert(_targetBSpline.Count, new BezierPoint(GetSceneView().pivot));
                    EditorUtility.SetDirty(_targetBSpline);
                    refreshSv = true;
                }
                if (GUILayout.Button("Set", EditorStyles.miniButtonMid, GUILayout.MinWidth(20f)))
                {
                    if (_targetSelectedID > -1)
                    {
                        Undo.RecordObject(_targetBSpline, "change pos");
                        _targetBSpline[_targetSelectedID].Position = GetSceneView().pivot;
                        EditorUtility.SetDirty(_targetBSpline);
                        refreshSv = true;
                    }
                }
                if (GUILayout.Button("Set SceneTarget", EditorStyles.miniButtonRight, GUILayout.MinWidth(20f)))
                {
                    if (_targetSelectedID > -1)
                    {
                        SceneView sv = GetSceneView();
                        sv.FixNegativeSize();
                        sv.pivot = _targetBSpline[_targetSelectedID].Position;
                        // sv.size = 10f;
                        // sv.LookAt(_targetBSpline[_targetSelectedID].Point);
                    }
                }
            }

            EditorGUILayout.EndHorizontal();

            var showHandles = GUILayout.Toggle(_showHandles, _showHandles ? "Hide Control Handles" : "Show Control Handles", EditorStyles.toolbarButton);
            if (_showHandles != showHandles)
            {
                _showHandles = showHandles;
                refreshSv    = true;
            }

            EditorGUILayout.Space();

            if (GUILayout.Button("Sort", EditorStyles.miniButton, GUILayout.MinWidth(20f)))
            {
                _cameraBSpline.Sort();
                if (_cameraBSpline.Count > 0)
                {
                    _cameraBSpline[0].Percent = 0f;
                    _cameraBSpline[_cameraBSpline.Count - 1].Percent = 1f;
                }

                _targetBSpline.Sort();
                if (_targetBSpline.Count > 0)
                {
                    _targetBSpline[0].Percent = 0f;
                    _targetBSpline[_targetBSpline.Count - 1].Percent = 1f;
                }

                AssetDatabase.SaveAssets();
            }

            if (refreshSv)
            {
                GetSceneView().Repaint();
            }

            EditorGUILayout.Space();

            _showPreviewCamera = GUILayout.Toggle(_showPreviewCamera, _showPreviewCamera ? "Hide Preview Camera" : "ShowPreview Camera", EditorStyles.toolbarButton);
            if (_showPreviewCamera)
            {
                EditorGUILayout.BeginHorizontal();
                _previewDuration = EditorGUILayout.FloatField(_previewDuration, EditorStyles.toolbarTextField);
                if (_previewDuration <= 0f)
                {
                    _previewDuration = 5f;
                }
                _autoPreview = GUILayout.Toggle(_autoPreview, _autoPreview ? "Stop" : "Go", EditorStyles.toolbarButton);
                _percent     = EditorGUILayout.Slider(_percent, 0f, 1f);
                EditorGUILayout.EndHorizontal();
                EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(PREVIEW_WIDTH, PREVIEW_HEIGHT), _previewRenderTexture, null, ScaleMode.ScaleToFit);
            }
        }
コード例 #54
0
 protected void Awake()
 {
     onPathCalculation += GetApproximateSplineLength;
     spline             = GetComponent <BezierSpline>();
 }
コード例 #55
0
 // Use this for initialization
 void Start()
 {
     spline = GetComponent <BezierSpline>();
 }
コード例 #56
0
    // Use this for initialization
    void Start()
    {
        t = 0;
        currentSpline = startingSpline;

        transform.position = currentSpline.GetPoint(t);
        transform.rotation = currentSpline.GetOrientation(t, Vector3.Lerp(currentSpline.startNode.transform.up, currentSpline.endNode.transform.up, t));

        lastForward = transform.forward;

        //currentSpline.GetComponent<MeshCollider>().enabled = true;
    }
コード例 #57
0
    void DrawEditBezierPatch(BezierSpline patch, int segs)
    {
        Sprite targetSprite = (Sprite)target;

        Vector3 fixedPoint;
        float distance;
        Camera cam = SceneView.currentDrawingSceneView.camera;

        //Tangent Handles
        if (!patch.linear) {
            Vector3 originalTangent0 = patch.tangetPos0;
            Vector3 originalTangent1 = patch.tangetPos1;
            distance = Vector3.Distance(patch.tangetPos0,cam.transform.position);
            fixedPoint = Handles.FreeMoveHandle(patch.tangetPos0,Quaternion.identity,0.01f*distance,Vector3.zero,Handles.RectangleCap);
            //Debug.Log(fixedPoint);

            if (originalTangent0 != fixedPoint) {
                //needsUndo = true;
                if (targetSprite.lock2D) {
                    fixedPoint = targetSprite.transform.InverseTransformPoint(fixedPoint);
                    fixedPoint.z = 0.0f;
                    fixedPoint = targetSprite.transform.TransformPoint(fixedPoint);
                }
                patch.tangetPos0 = fixedPoint;
                if (Event.current.control) {
                    patch.localNormal0 = SnapVector3(patch.localNormal0,SpriteWorldManager.current.gridSize*0.5f);
                    patch.localNormal0.Normalize();
                }
                if (targetSprite.lock2D) {
                    patch.localNormal0.z = 0.0f;
                }
            }

            distance = Vector3.Distance(patch.tangetPos1,cam.transform.position);
            fixedPoint = Handles.FreeMoveHandle(patch.tangetPos1,Quaternion.identity,0.01f*distance,Vector3.zero,Handles.RectangleCap);
            if (originalTangent1 != fixedPoint) {
                //needsUndo = true;
                if (targetSprite.lock2D) {
                    fixedPoint = targetSprite.transform.InverseTransformPoint(fixedPoint);
                    fixedPoint.z = 0.0f;
                    fixedPoint = targetSprite.transform.TransformPoint(fixedPoint);
                }
                patch.tangetPos1 = fixedPoint;
                if (Event.current.control) {
                    patch.localNormal1 = SnapVector3(patch.localNormal1,SpriteWorldManager.current.gridSize*0.5f);
                    patch.localNormal0.Normalize();
                }
                if (targetSprite.lock2D) {
                    patch.localNormal1.z = 0.0f;
                }
            }
        }

        DrawBezierPatch(patch,segs);
    }
コード例 #58
0
ファイル: BezierPoint.cs プロジェクト: justvdlinde/Holopet
 public BezierPoint(BezierSpline spline) : this(spline, Vector3.zero)
 {
 }
コード例 #59
0
ファイル: TrackFollower.cs プロジェクト: maxlinke/Sekai-Aces
 public void ChangeSpline(BezierSpline newSpline)
 {
     spline   = newSpline;
     position = newSpline.GetClosestPosition(transform.position);
 }
コード例 #60
0
    void SetTarget()
    {
        if (goingForward) {
            if (segments [current].GetComponent<RailComponent> ().next != null) {
                Debug.Log(current);
                target = segments [current].GetComponent<RailComponent> ().next;
                spline = segments [current].GetComponent<RailComponent> ().rail;
        //				if(spline.Loop && (segments[current].GetComponent<RailComponent>().head)){
        //					lastHead = current;
        ////					Debug.Log("LH: "+lastHead);
        //					current ++;
        //				}else if(spline.Loop && (segments[current].GetComponent<RailComponent>().tail)){
        //					lastTail = current;
        //					current = lastHead;
        //				}else{
                current = segments[current].GetComponent<RailComponent> ().next.GetComponent<RailComponent>().segNum;
        //				}
            } else {
                Debug.Log("FEELS LIKE FALLING");
                player.playerMode = PlayerMode.Jump;
                GetComponent<Rigidbody>().AddForce(segments[current].transform.forward*(8000f));
                GetComponent<Rigidbody>().AddForce(this.transform.up*(9000f));

            }
        } else {
            if (segments [current].GetComponent<RailComponent> ().last != null) {
        //				Debug.Log(current);
        //				DeDebugbug.Log("LT: "+lastTail);
                target = segments [current].GetComponent<RailComponent> ().last;
                spline = segments [current].GetComponent<RailComponent> ().rail;
        //				if(spline.Loop && (segments[current].GetComponent<RailComponent>().head)){
        //					lastHead = current;
        //					current = lastTail;
        //				} else if(spline.Loop && (segments[current].GetComponent<RailComponent>().tail)){
        //					Debug.Log("LT: "+lastTail);
        //					lastTail = current;
        //					current --;
        //				} else{
        //					Debug.Log("Still Happening");
                current = segments[current].GetComponent<RailComponent> ().last.GetComponent<RailComponent>().segNum;
        //				}
            } else {
                Debug.Log("FEELS LIKE FALLING");
                player.playerMode = PlayerMode.Jump;
                GetComponent<Rigidbody>().AddForce(segments[current].transform.forward*(-8000f));
                GetComponent<Rigidbody>().AddForce(this.transform.up*(9000f));

            }
        }
    }