/// <summary> /// Given each sub-spline from one node to the next in our path, stitch them all together to form one large bezier spline. /// </summary> public void CalculatePathSpline() { // Quick way to remove all previous curves and points. // One curve is created during Reset(), so we have to clear that out too selectedPathSpline.Reset(); selectedPathSpline.RemoveCurve(); for (int currentNodeIndex = 0; currentNodeIndex < selectedPath.Count - 1; currentNodeIndex++) { selectedPathSpline.AddCurve(); // -- Set the control point mode. // Due to the way that I set up the node positions, free mode is the only one that looks good. I could use Aligned or Mirrored if I added more inbetween nodes, but my setup for creating nodes was kinda garbage // Free mode only is fine for now selectedPathSpline.SetControlPointMode(3 * currentNodeIndex, controlPointMode); selectedPathSpline.SetControlPointMode(3 * currentNodeIndex + 3, controlPointMode); // Find the index of the sub-spline we want, in the node. // We have to do this search, since we store multiple sub-splines in each node int index = selectedPath[currentNodeIndex].connectedNodes.IndexOf(selectedPath[currentNodeIndex + 1]); BezierSpline subSpline = selectedPath[currentNodeIndex].connectedNodePaths[index]; Vector3 toNode = selectedPath[currentNodeIndex].transform.position - transform.position; // -- Copy over each control point of the spline // Need to do this in this weird order, because we have to set the control points after the pivot points. // BezierSpline.SetControlPoints should probably get refactored to include an overload method to avoid this, but oh well selectedPathSpline.SetControlPoint(3 * currentNodeIndex + 0, toNode + subSpline.GetControlPoint(0)); selectedPathSpline.SetControlPoint(3 * currentNodeIndex + 1, toNode + subSpline.GetControlPoint(1)); selectedPathSpline.SetControlPoint(3 * currentNodeIndex + 3, toNode + subSpline.GetControlPoint(3)); selectedPathSpline.SetControlPoint(3 * currentNodeIndex + 2, toNode + subSpline.GetControlPoint(2)); } }
public override void OnInspectorGUI() { //DrawDefaultInspector (); 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, "AddCurve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } if (GUILayout.Button("ResetCurve")) { Undo.RecordObject(spline, "ResetCurve"); spline.Reset(); EditorUtility.SetDirty(spline); } }
public override void OnInspectorGUI(){ //DrawDefaultInspector(); 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, "AddCurve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } if (GUILayout.Button("Reset Curve")) { Undo.RecordObject(spline, "Reset Curve"); spline.Reset(); EditorUtility.SetDirty(spline); } }
public void SetPoints() { targetSpline = GetComponent <BezierSpline>(); targetSpline.Reset(); int requiredCurveCount = splinePointTargetsTranforms.Length / 4; if (splinePointTargetsTranforms.Length % 4 != 0) { requiredCurveCount++; } for (int i = 0; i < requiredCurveCount; i++) { targetSpline.AddCurve(); } splinePointPositions = new Vector3[splinePointTargetsTranforms.Length]; for (int i = 0; i < splinePointTargetsTranforms.Length; i++) { splinePointPositions[i] = splinePointTargetsTranforms[i].transform.localPosition; } targetSpline.SetMultipleControlPoints(splinePointPositions, pointMode); }
protected override void Initialize() { base.Initialize(); Setup.Initialize(GraphicsDevice); MySpline = new BezierSpline(); MySpline.Reset(); GetSpline = MySpline; MySplineWalker = new Car(); MySplineWalker.CreateSplineWalker(MySpline, SplineWalker.SplineWalkerMode.Once, 7); MySplineWalker.LoadContent(Editor.Content, Editor.Font); MySplineMarker = new Marker(); MySplineMarker.CreateSplineWalker(MySpline, SplineWalker.SplineWalkerMode.Once, 0, false, autoStart: false); MySplineMarker.LoadContent(Editor.Content); MoveSplineToScreenCenter(); SetMultiSampleCount(8); Editor.SetDisplayStyle = Forms.Services.GFXService.DisplayStyle.TopRight; Editor.ShowCursorPosition = false; Editor.ShowFPS = false; }
private void CurveEditor() { if (spline == null) { spline = master.spline; } EditorGUI.BeginChangeCheck(); 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(selectedIndex); selectedIndex = -1; EditorUtility.SetDirty(spline); } if (GUILayout.Button("Reset")) { Undo.RecordObject(spline, "Reset"); spline.Reset(); master.Reset(); selectedIndex = -1; EditorUtility.SetDirty(spline); } GUILayout.BeginVertical("box"); GUILayout.Space(5); bool loop = EditorGUILayout.Toggle("Loop", spline.Loop); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(spline, "Toggle Loop"); EditorUtility.SetDirty(spline); spline.Loop = loop; } GUILayout.Label(" Curve Lenght: " + spline.GetCurveLenght()); GUILayout.Space(5); GUILayout.EndVertical(); if (selectedIndex >= 0 && selectedIndex < spline.ControlPointCount) { DrawSelectedPointInspector(); } else { GUILayout.BeginVertical("box"); GUILayout.Space(5); GUILayout.Label(" Select point to edit!"); GUILayout.Space(5); GUILayout.EndVertical(); } }
public void UpdateTireBezier() { if (TireSpline == null) { //first time, create spline TireSpline = gameObject.AddComponent <BezierSpline>(); TireSpline.Reset(); TireSpline.AddCurve(); TireSpline.AddCurve(); TireSpline.AddCurve(); TireSpline.AddCurve(); } float SmoothValue = 0.025f; Vector3 p1 = new Vector3(RimRadius, RimWidth / 2, 0); TireSpline.SetControlPoint(0, p1); TireSpline.SetControlPoint(1, p1 + new Vector3(Mathf.Min(SmoothValue, TireHeight * _SideWallSize), 0, 0)); //Mathf.Max (-value,(WheelDiameter+TireHeight*_SideWallSize) - _WheelDiameter) Vector3 p2 = new Vector3(RimRadius + TireHeight * _SideWallSize, TireWidth / 2, 0); TireSpline.SetControlPoint(3, p2); TireSpline.SetControlPoint(2, p2 + new Vector3(Mathf.Max(-SmoothValue, -TireHeight * _SideWallSize), 0, 0)); TireSpline.SetControlPoint(4, p2 + new Vector3(TireHeight * (1 - _SideWallSize) * _Curvature, 0, 0)); Vector3 p3 = new Vector3(RimRadius + TireHeight, (TireWidth / 2) * _FlatPart, 0); TireSpline.SetControlPoint(6, p3); TireSpline.SetControlPoint(5, p3 + new Vector3(0, (TireWidth / 2) * (1 - _FlatPart) * _Curvature, 0)); TireSpline.SetControlPoint(7, p3 + new Vector3(0, Mathf.Max(-SmoothValue, Mathf.Clamp01(-p3.y)), 0)); Vector3 p4 = new Vector3(RimRadius + TireHeight, (-TireWidth / 2) * _FlatPart, 0); TireSpline.SetControlPoint(9, p4); TireSpline.SetControlPoint(8, p4 + new Vector3(0, Mathf.Min(SmoothValue, Mathf.Clamp01(-p4.y)), 0)); TireSpline.SetControlPoint(10, p4 + new Vector3(0, (-TireWidth / 2) * (1 - _FlatPart) * _Curvature, 0)); Vector3 p5 = new Vector3(RimRadius + TireHeight * _SideWallSize, -TireWidth / 2, 0); TireSpline.SetControlPoint(12, p5); TireSpline.SetControlPoint(11, p5 + new Vector3(TireHeight * (1 - _SideWallSize) * _Curvature, 0, 0)); TireSpline.SetControlPoint(13, p5 + new Vector3(Mathf.Max(-SmoothValue, -TireHeight * _SideWallSize), 0, 0)); Vector3 p6 = new Vector3(RimRadius, -RimWidth / 2, 0); TireSpline.SetControlPoint(15, p6); TireSpline.SetControlPoint(14, p6 + new Vector3(Mathf.Min(SmoothValue, TireHeight * _SideWallSize), 0, 0)); }
/// <summary> /// This overrides the onInspectorGUI which modifies the inspector of the class bezierSpline /// </summary> public override void OnInspectorGUI() { DrawDefaultInspector(); spline = target as BezierSpline; if (GUILayout.Button("Add Curve")) { Undo.RecordObject(spline, "Add Curve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } if (GUILayout.Button("Reset Curve")) { spline.Reset(); EditorUtility.SetDirty(spline); } }
/// <summary> /// This overrides the onInspectorGUI which modifies the inspector of the class bezierSpline /// </summary> public override void OnInspectorGUI() { //DrawDefaultInspector(); spline = target as BezierSpline; spline.endPoint = GUILayout.Toggle(spline.endPoint, "Final Path"); if (selectedIndex >= 0 && selectedIndex < spline.ControlPointCount) { DrawSelectedPointInspector(); } if (GUILayout.Button("Add Curve")) { Undo.RecordObject(spline, "Add Curve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } if (spline.transform.parent.GetComponent <pathSystem>() != null) { if (GUILayout.Button("Split Curve")) { Undo.RecordObject(spline, "Split Curve"); spline.SplitCurve(); EditorUtility.SetDirty(spline); } } if (spline.transform.parent.GetComponent <pathSystem>() != null) { if (GUILayout.Button("Join Curve (Ends must meet)")) { Undo.RecordObject(spline, "Join Spline"); spline.joinSpline(); EditorUtility.SetDirty(spline); } } if (GUILayout.Button("Reset Curve")) { spline.Reset(0); EditorUtility.SetDirty(spline); } }
public void CreatePath() { DeletePath(); m_PathGO = new GameObject("Cam Path"); m_PathGO.AddComponent<BezierSpline>(); m_Path = m_PathGO.GetComponent<BezierSpline>(); m_Path.Reset(); //if(m_CamSysParent != null) // m_Path.transform.parent = m_PathParent; //else m_Path.transform.parent = (new GameObject("CamPathRoot")).transform; if(m_EndTrans != null && m_StartTrans != null) { SetPath(); } else{ Debug.LogError(" Start and End points not set!! "); } }
public override void OnInspectorGUI() { base.OnInspectorGUI(); spline = (BezierSpline)target; // Reset button if (GUILayout.Button("Reset")) { Undo.RecordObject(spline, "Reset"); spline.Reset(); EditorUtility.SetDirty(spline); } // Add curve button if (GUILayout.Button("Add Curve")) { Undo.RecordObject(spline, "Add Curve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } }
void RetracePath(Node startNode, Node endNode) { spline.Reset(); List <Node> path = new List <Node>(); Node currentNode = endNode; int i = 0; while (currentNode != startNode) { spline.points[i] = currentNode.worldPosition; path.Add(currentNode); currentNode = currentNode.parent; i++; if (spline.points.Length == i) { spline.AddCurve(); } } path.Reverse(); grid.path = path; }
////////////////////////////////////////////////////////////////////////////////////////// #region Methods ////////////////////////////////////////////////////////////////////////////////////////// public void reset() { if (m_bezierSpline) { m_bezierSpline.Reset(); m_splinePointCount = 0; } if (m_particles) { m_particles.Stop(); m_particles.Clear(); } if (m_lineWalker) { m_lineWalker.stop(); } m_currentState = DrawState.Uncreated; }
public override void OnInspectorGUI() { DrawDefaultInspector(); spline = target as BezierSpline; EditorGUI.BeginChangeCheck(); bool loop = EditorGUILayout.Toggle("Loop", spline.Loop); int linearApproxSteps = EditorGUILayout.IntField("LinearApproxSteps", spline.LinearApproxSteps); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(spline, "Spline InspectorChange"); EditorUtility.SetDirty(spline); spline.Loop = loop; spline.LinearApproxSteps = linearApproxSteps; } if (selectedIndex >= 0 && selectedIndex < spline.ControlPointCount) { DrawSelectedPointInspector(); } if (GUILayout.Button("Add Curve")) { Undo.RecordObject(spline, "AddCurve"); spline.AddCurve(); EditorUtility.SetDirty(spline); } if (GUILayout.Button("ResetCurve")) { Undo.RecordObject(spline, "ResetCurve"); spline.Reset(); EditorUtility.SetDirty(spline); } if (GUILayout.Button("DrawTextMarker")) { Undo.RecordObject(spline, "Draw text marker"); spline.AddDistanceMarker(); EditorUtility.SetDirty(spline); } }
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(); }
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 (); }
public static void DrawSplineInspectorGUI(BezierSpline[] splines) { if (splines.Length == 0) { return; } for (int i = 0; i < splines.Length; i++) { if (splines[i].Count < 2) { if (GUILayout.Button("Initialize Spline")) { Object[] selection = Selection.objects; for (int j = 0; j < splines.Length; j++) { BezierSpline spline = splines[j]; if (spline.Count < 2) { bool isSplineSelected = false; for (int k = 0; k < selection.Length; k++) { if (selection[k] == spline || selection[k] == spline.transform || selection[k] == spline.gameObject) { isSplineSelected = true; break; } } spline.Reset(); // Try to continue showing spline's scene gizmos after initialization by keeping // either the spline or a point of it selected if (!isSplineSelected) { System.Array.Resize(ref selection, selection.Length + 1); selection[selection.Length - 1] = spline[0].gameObject; } } } Selection.objects = selection; GUIUtility.ExitGUI(); } return; } } Color c = GUI.color; bool hasMultipleDifferentValues = false; bool loop = splines[0].loop; for (int i = 1; i < splines.Length; i++) { if (splines[i].loop != loop) { hasMultipleDifferentValues = true; break; } } EditorGUI.showMixedValue = hasMultipleDifferentValues; EditorGUI.BeginChangeCheck(); loop = EditorGUILayout.Toggle("Loop", loop); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Toggle Loop"); splines[i].loop = loop; } SceneView.RepaintAll(); } hasMultipleDifferentValues = false; bool drawGizmos = splines[0].drawGizmos; for (int i = 1; i < splines.Length; i++) { if (splines[i].drawGizmos != drawGizmos) { hasMultipleDifferentValues = true; break; } } EditorGUI.showMixedValue = hasMultipleDifferentValues; EditorGUI.BeginChangeCheck(); drawGizmos = EditorGUILayout.Toggle("Draw Runtime Gizmos", drawGizmos); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Toggle Draw Gizmos"); splines[i].drawGizmos = drawGizmos; } SceneView.RepaintAll(); } if (drawGizmos) { hasMultipleDifferentValues = false; Color gizmoColor = splines[0].gizmoColor; for (int i = 1; i < splines.Length; i++) { if (splines[i].gizmoColor != gizmoColor) { hasMultipleDifferentValues = true; break; } } EditorGUI.showMixedValue = hasMultipleDifferentValues; EditorGUI.BeginChangeCheck(); gizmoColor = EditorGUILayout.ColorField(" Gizmo Color", gizmoColor); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Change Gizmo Color"); splines[i].gizmoColor = gizmoColor; } SceneView.RepaintAll(); } hasMultipleDifferentValues = false; int gizmoSmoothness = splines[0].gizmoSmoothness; for (int i = 1; i < splines.Length; i++) { if (splines[i].gizmoSmoothness != gizmoSmoothness) { hasMultipleDifferentValues = true; break; } } EditorGUI.showMixedValue = hasMultipleDifferentValues; EditorGUI.BeginChangeCheck(); gizmoSmoothness = EditorGUILayout.IntSlider(" Gizmo Smoothness", gizmoSmoothness, 1, 30); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Change Gizmo Smoothness"); splines[i].gizmoSmoothness = gizmoSmoothness; } SceneView.RepaintAll(); } } EditorGUI.showMixedValue = false; EditorGUILayout.Space(); GUI.color = AUTO_CONSTRUCT_SPLINE_BUTTON_COLOR; ShowAutoConstructButton(splines, "Construct Linear Path", SplineAutoConstructMode.Linear); ShowAutoConstructButton(splines, "Auto Construct Spline", SplineAutoConstructMode.Smooth1); ShowAutoConstructButton(splines, "Auto Construct Spline (method #2)", SplineAutoConstructMode.Smooth2); GUI.color = c; }
private void OnSceneGUI() { //float currentTime = (float)EditorApplication.timeSinceStartup; spline = target as BezierSpline; handleTransform = spline.transform; handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity; /* if (GUIUtility.hotControl > 0 && spline.numberOfClicks>0) * { * Debug.Log("clicked on some shit"+ GUIUtility.hotControl+" sdfjsdjfjh "); * // GUIUtility.GetControlID(); * //Vector3 currentPos = Handles * // GUIUtility.GetStateObject * // Debug.Log("list of point space"+listOfControlIds.IndexOf(GUIUtility.hotControl)); * * //GUIUtility.GetStateObject(GUIUtility.hotControl); * };*/ Vector3 p0 = ShowPoint(0); if (toggleAdd) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.ArrowPlus); } else { if (toggleRemove) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.ArrowMinus); } } Handles.BeginGUI(); GUILayout.BeginArea(new Rect(0, 5, 220, 200)); GUILayout.Label((Texture)Resources.Load("evvvvil-3d-splines")); //GUI.skin.button.fontSize = 12; GUILayout.BeginHorizontal(); //GUI.skin.button.padding = new RectOffset(0,0,0,0); GUILayout.Space(14); GUISkin mySkin = (GUISkin)Resources.Load("evvvvil-spline-skin"); SetAdd(GUILayout.Toggle(toggleAdd, "", mySkin.customStyles[0])); GUILayout.Space(11); GUI.Box(new Rect(51, 63, 100, 100), "", mySkin.customStyles[3]); SetRemove(GUILayout.Toggle(toggleRemove, "", mySkin.customStyles[1])); /* * if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) * { * Debug.Log("Mouse over!"); * } * * else * { * Debug.Log("Mouse somewhere else"); * } */ GUILayout.EndHorizontal(); //GUI.skin.button.fontSize = 8; //GUI.skin.button.alignment = TextAnchor.MiddleCenter; bool yobro = GUILayout.Button("", mySkin.customStyles[2]); if (yobro) { spline.Reset(); } GUILayout.EndArea(); GUILayout.BeginArea(new Rect(14, Screen.height - 70, 500, 25)); GUILayout.Label(sarcasticString); GUILayout.EndArea(); Handles.EndGUI(); // Debug.Log("before main gui loop number of points is: "+spline.ControlPointCount); for (int i = 1; i < spline.ControlPointCount; i += 3) { // Debug.Log("loop index is: " + i); Vector3 p1 = ShowPoint(i); Vector3 p2 = ShowPoint(i + 1); // Debug.Log("loop index is i+1: " + (i+1)); Vector3 p3 = ShowPoint(i + 2); // Debug.Log("loop index is i+2: " + (i+2)); if ((spline.ShowHandlesMode == BezierShowHandlesMode.All || (spline.ShowHandlesMode == BezierShowHandlesMode.OnlySelected && (selectedIndex > -1 && (selectedIndex == i - 1 || selectedIndex == i - 2 || selectedIndex == i) || (spline.numberOfClicks - i < 3 && toggleAdd)))) && !toggleRemove) { if (i - 2 > 0) { Vector3 previousP = ShowPoint(i - 2); Handles.color = Color.gray; Handles.DrawLine(previousP, p0); } Handles.color = Color.gray; Handles.DrawLine(p0, p1); } if (i + 2 < spline.numberOfClicks) { Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f); } p0 = p3; } /*if (spline.ShowDir) * { * ShowDirections(); * }*/ /* code tkane from: * * http://forum.unity3d.com/threads/solved-custom-editor-onscenegui-scripting.34137/ * */ // int controlID = GUIUtility.GetControlID(spline, FocusType.Passive); Event current = Event.current; if (current.type == EventType.layout) { //int controlID = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive); int controlID = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlID); if (doTheTwist >= 0) { if (spline.numberOfClicks % 3 == 1) { Debug.Log("throw bug?"); spline.numberOfClicks += 2; } spline.RemoveControlPoint(doTheTwist); doTheTwist = -1; } } else if (current.type == EventType.MouseDown && toggleAdd) { if (current.button == 0) { current.Use(); sarcasticString = GetSarcasm(); if (Camera.current != null) { SetPointWithMouse(current); if (spline.numberOfClicks % 3 == 0 && spline.numberOfClicks > 0) { spline.AddCurve(); } spline.numberOfClicks++; } } } else if (current.type == EventType.MouseDrag && toggleAdd) { currentLife++; if (current.button == 0) { current.Use(); if (Camera.current != null) { SetPointWithMouse(current); } } } else if (current.type == EventType.MouseUp && toggleAdd) { //Debug.Log("mouseup "); if (current.button == 0) { current.Use(); spline.numberOfClicks += 2; } } else if (current.type == EventType.MouseMove && toggleAdd) { if (spline.numberOfClicks % 3 == 1) { //Debug.Log("throw bug?"); spline.numberOfClicks += 2; } } /* end of code */ }
// Use this for initialization void Start() { randomSpline.Reset(); int totalCurves = Random.Range(30, 50); for (int i = 1; i < totalCurves; i++) { randomSpline.AddCurve(); } Vector3 point = Vector3.zero; float radiusX = 10f, radiusY = 20f; float radiusAmount = 0f; for (int i = 0; i < randomSpline.CurveCount; i++) { radiusAmount = ((float)i / randomSpline.CurveCount) * (2 * Mathf.PI); point = new Vector3(radiusX * Mathf.Cos(radiusAmount), 0f, radiusY * Mathf.Sin(radiusAmount)); //+ //new Vector3(Random.Range (-0.5f, 0.5f), 0f, Random.Range (-0.5f, 0.5f)); point = radiusSize * point; randomSpline.SetControlPointMode(i * 3, BezierControlPointMode.Free); randomSpline.SetControlPoint(i * 3, point); if (i * 3 - 1 >= 0) { randomSpline.SetControlPoint(i * 3 - 1, point); } if (i * 3 + 1 < randomSpline.ControlPointCount) { randomSpline.SetControlPoint(i * 3 + 1, point); } } randomSpline.SetControlPoint(randomSpline.ControlPointCount - 1, point); Vector3 lastPoint = randomSpline.GetControlPoint(0); for (int i = 1; i < randomSpline.CurveCount; i++) { point = randomSpline.GetControlPoint(i * 3); Vector3 crossVector = Vector3.Cross(point - lastPoint, Vector3.up); Vector3 p1 = point + 0.5f * roadSize * crossVector.normalized; Vector3 p2 = point - 0.5f * roadSize * crossVector.normalized; meshBuilder.Vertices.Add(p1); meshBuilder.Vertices.Add(point); meshBuilder.Vertices.Add(p2); lastPoint = point; } int baseIndex = 0; int sizeX = 2; int sizeY = randomSpline.CurveCount - 2; int vi = baseIndex; for (int y = 0; y < sizeY; y++, vi++) { for (int x = 0; x < sizeX; x++, vi++) { meshBuilder.AddTriangle(vi, vi + sizeX + 1, vi + 1); meshBuilder.AddTriangle(vi + 1, vi + sizeX + 1, vi + sizeX + 2); if (y == sizeY - 1) { meshBuilder.AddTriangle(vi + sizeX + 1, baseIndex + x, vi + sizeX + 2); meshBuilder.AddTriangle(baseIndex + x + 1, vi + sizeX + 2, baseIndex + x); } } } GetComponent <MeshFilter> ().mesh = meshBuilder.CreateMesh(); }
public static void DrawSplineInspectorGUI(BezierSpline[] splines) { if (splines.Length == 0) { return; } for (int i = 0; i < splines.Length; i++) { if (splines[i].Count < 2) { if (GUILayout.Button("Initialize Spline")) { Object[] selection = Selection.objects; for (int j = 0; j < splines.Length; j++) { BezierSpline spline = splines[j]; if (spline.Count < 2) { bool isSplineSelected = false; for (int k = 0; k < selection.Length; k++) { if (selection[k] == spline || selection[k] == spline.transform || selection[k] == spline.gameObject) { isSplineSelected = true; break; } } spline.Reset(); // Try to continue showing spline's scene gizmos after initialization by keeping // either the spline or a point of it selected if (!isSplineSelected) { Array.Resize(ref selection, selection.Length + 1); selection[selection.Length - 1] = spline[0].gameObject; } } } Selection.objects = selection; GUIUtility.ExitGUI(); } return; } } Color c = GUI.color; EditorGUI.showMixedValue = HasMultipleDifferentValues(splines, (s1, s2) => s1.loop == s2.loop); EditorGUI.BeginChangeCheck(); bool loop = EditorGUILayout.Toggle("Loop", splines[0].loop); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { BezierSpline spline = splines[i]; Undo.RecordObject(spline, "Toggle Loop"); spline.loop = loop; spline.Internal_SetDirtyImmediatelyWithUndo("Toggle Loop"); } SceneView.RepaintAll(); } EditorGUI.showMixedValue = HasMultipleDifferentValues(splines, (s1, s2) => s1.drawGizmos == s2.drawGizmos); EditorGUI.BeginChangeCheck(); bool drawGizmos = EditorGUILayout.Toggle("Draw Runtime Gizmos", splines[0].drawGizmos); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Toggle Draw Gizmos"); splines[i].drawGizmos = drawGizmos; } SceneView.RepaintAll(); } if (drawGizmos) { EditorGUI.indentLevel++; EditorGUI.showMixedValue = HasMultipleDifferentValues(splines, (s1, s2) => s1.gizmoColor == s2.gizmoColor); EditorGUI.BeginChangeCheck(); Color gizmoColor = EditorGUILayout.ColorField("Gizmo Color", splines[0].gizmoColor); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Change Gizmo Color"); splines[i].gizmoColor = gizmoColor; } SceneView.RepaintAll(); } EditorGUI.showMixedValue = HasMultipleDifferentValues(splines, (s1, s2) => s1.gizmoSmoothness == s2.gizmoSmoothness); EditorGUI.BeginChangeCheck(); int gizmoSmoothness = EditorGUILayout.IntSlider("Gizmo Smoothness", splines[0].gizmoSmoothness, 1, 30); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Change Gizmo Smoothness"); splines[i].gizmoSmoothness = gizmoSmoothness; } SceneView.RepaintAll(); } EditorGUI.indentLevel--; } EditorGUI.showMixedValue = false; EditorGUI.BeginChangeCheck(); bool showControlPoints = EditorGUILayout.Toggle("Show Control Points", ShowControlPoints); if (EditorGUI.EndChangeCheck()) { ShowControlPoints = showControlPoints; SceneView.RepaintAll(); } if (showControlPoints) { EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); bool showControlPointDirections = EditorGUILayout.Toggle("Show Directions", ShowControlPointDirections); if (EditorGUI.EndChangeCheck()) { ShowControlPointDirections = showControlPointDirections; SceneView.RepaintAll(); } EditorGUI.indentLevel--; } EditorGUI.BeginChangeCheck(); bool showEndPointLabels = EditorGUILayout.Toggle("Show Point Indices", ShowEndPointLabels); if (EditorGUI.EndChangeCheck()) { ShowEndPointLabels = showEndPointLabels; SceneView.RepaintAll(); } EditorGUI.BeginChangeCheck(); bool showNormals = EditorGUILayout.Toggle("Show Normals", ShowNormals); if (EditorGUI.EndChangeCheck()) { ShowNormals = showNormals; SceneView.RepaintAll(); } EditorGUI.showMixedValue = HasMultipleDifferentValues(splines, (s1, s2) => s1.Internal_AutoCalculatedNormalsAngle == s2.Internal_AutoCalculatedNormalsAngle); EditorGUI.BeginChangeCheck(); float autoCalculatedNormalsAngle = EditorGUILayout.FloatField("Auto Calculated Normals Angle", splines[0].Internal_AutoCalculatedNormalsAngle); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { Undo.RecordObject(splines[i], "Change Normals Angle"); splines[i].Internal_AutoCalculatedNormalsAngle = autoCalculatedNormalsAngle; splines[i].Internal_SetDirtyImmediatelyWithUndo("Change Normals Angle"); } SceneView.RepaintAll(); } EditorGUI.showMixedValue = false; EditorGUILayout.Space(); GUI.color = AUTO_CONSTRUCT_SPLINE_BUTTON_COLOR; ShowAutoConstructButton(splines, "Construct Linear Path", SplineAutoConstructMode.Linear); ShowAutoConstructButton(splines, "Auto Construct Spline", SplineAutoConstructMode.Smooth1); ShowAutoConstructButton(splines, "Auto Construct Spline 2", SplineAutoConstructMode.Smooth2); GUILayout.BeginHorizontal(); if (GUILayout.Button("Auto Calculate Normals")) { for (int i = 0; i < splines.Length; i++) { BezierSpline spline = splines[i]; Undo.RecordObject(spline, "Auto Calculate Normals"); try { spline.Internal_AutoCalculateNormals = true; spline.Internal_SetDirtyImmediatelyWithUndo("Auto Calculate Normals"); } finally { spline.Internal_AutoCalculateNormals = false; } } SceneView.RepaintAll(); } EditorGUI.BeginChangeCheck(); bool autoCalculateNormalsEnabled = GUILayout.Toggle(Array.Find(splines, (s) => s.Internal_AutoCalculateNormals), AUTO_CONSTRUCT_ALWAYS_TEXT, GUI.skin.button, EditorGUIUtility.wideMode ? GL_WIDTH_100 : GL_WIDTH_60); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < splines.Length; i++) { BezierSpline spline = splines[i]; Undo.RecordObject(spline, "Change Auto Calculate Normals"); spline.Internal_AutoCalculateNormals = autoCalculateNormalsEnabled; spline.Internal_SetDirtyImmediatelyWithUndo("Change Auto Calculate Normals"); } SceneView.RepaintAll(); } GUILayout.EndHorizontal(); GUI.color = c; }
Boolean GenTrackDone() { if (!meshObject.activeSelf) { meshObject.SetActive(true); } level = 0; spline.Reset(); spline.firstTime = true; _lastCurve = false; DestroyTrack(); //destroy every point and collider GameObject totalPoints = Convert.ToInt32((trackLenght * MAX_POINTS) / MAX_LENGHT) / 3; totalPoints = totalPoints * 3; //define boundaries maxX = transform.position.x + totalPoints * fieldDimension; minX = transform.position.x - totalPoints * fieldDimension; maxZ = transform.position.z + totalPoints * fieldDimension; minZ = transform.position.z - totalPoints * fieldDimension; //Initialize Structures curvePoints = new List <List <Vector3> >(); directions = new List <float>(); direction = (float)(random.NextDouble() * 360); //start from a random direction Vector3 startPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z); //but on a center point float howFar = farPointDistance + farPointDistance * (1 - maxAngleD / 45); farReturnPoint = Support.MovePoint(startPoint, (float)(direction - 180), howFar); //GameObject pointObject = Instantiate(pointPrefab, // farReturnPoint, // Quaternion.identity) as GameObject; for (int i = 0; i < totalPoints / 3; i++) //foreach curve { List <Vector3> newCurvePoint = new List <Vector3>(); Vector3 secPoint; if (i == 0) { newCurvePoint.Add(startPoint); secPoint = randomPoint(startPoint, direction); } else { newCurvePoint.Add(curvePoints[curvePoints.Count - 1][3]); //add the last point of the previous curve as my first secPoint = Support.MovePoint(newCurvePoint[0], direction, segmentLen); //go "random" directions.Add(direction); } if (level != 0) { secPoint = new Vector3(secPoint.x, RAISE * level, secPoint.z); level = 0; } Vector3 trdpoint = randomPoint(secPoint, direction); Vector3 frtPoint = randomPoint(trdpoint, direction); newCurvePoint.Add(secPoint); newCurvePoint.Add(trdpoint); newCurvePoint.Add(frtPoint); if (!correctSpline(newCurvePoint, false)) { return(false); } curvePoints.Add(newCurvePoint); //buildSpline(newCurvePoint); } fromHereReach = curvePoints.Count; //head for the far return point, that is placed at the right opposite direction of the first point int k = 0; Vector3 lastPoint = curvePoints[curvePoints.Count - 1][3]; while (Vector3.Distance(lastPoint, farReturnPoint) > segmentLen * 4) { List <Vector3> newCurve = reachPointCurve(ref lastPoint); if (level != 0) { newCurve[1] = new Vector3(newCurve[1].x, RAISE * level, newCurve[1].z); level = 0; } if (!correctSpline(newCurve, false)) { return(false); } curvePoints.Add(newCurve); k++; if (k >= totalPoints / 2) { return(false); } } //now head for the initial point k = 0; while (lastPoint != startPoint) { List <Vector3> newCurve = reachFirstPoint(ref lastPoint, startPoint); if (level != 0) { newCurve[1] = new Vector3(newCurve[1].x, RAISE * level, newCurve[1].z); level = 0; } if (!correctSpline(newCurve, _lastCurve)) { return(false); } curvePoints.Add(newCurve); k++; if (k >= totalPoints / 2) { return(false); } } pointsObjects = new List <GameObject>(); //CreateDots(); mesh.CreateMesh(); spline.curves = new Dictionary <int, List <Vector3> >(); foreach (GameObject obj in GameObject.FindGameObjectsWithTag("ControlMesh")) { Destroy(obj); } List <Vector3> firstCurve = curvePoints[0]; Vector3 pos = Bezier.GetPoint(firstCurve[0], firstCurve[1], firstCurve[2], firstCurve[3], 0); Vector3 rot1 = Bezier.GetFirstDerivative(firstCurve[0], firstCurve[1], firstCurve[2], firstCurve[3], 0); Vector3 rot2 = Bezier.GetFirstDerivative(firstCurve[0], firstCurve[1], firstCurve[2], firstCurve[3], 0.5f); GameManager.GetComponent <GameManager>().SetStartPoint(pos, rot1); GameManager.GetComponent <GameManager>().isTrack = true; GameManager.GetComponent <GameManager>().EnableRace(); return(true); }
void OnEnable() { //setting up the sandworm object //because the sandworm is constantly being changed in maya Spline.Reset(); List <Vector3> splinePoints = new List <Vector3> (); for (int i = 0; i < SplineNodes.Length; i++) { splinePoints.Add(SplineNodes [i].localPosition); } Spline.AddPoints(splinePoints.ToArray()); NormalizedPosition = 0f; GameObject sw = GameObject.Find("Sandworm"); #if UNITY_EDITOR UnityEditor.PrefabUtility.RevertPrefabInstance(sw); #endif Transform [] wormTransforms = sw.transform.GetComponentsInChildren <Transform> (); List <Transform> tailTransformsSorted = new List <Transform> (); foreach (Transform t in wormTransforms) { if (t.name == "Root") { Worm = t; } else if (t.name.Contains("Tail_") && t.name != "Tail_39") { tailTransformsSorted.Add(t); } } tailTransformsSorted.Sort((t1, t2) => t1.name.CompareTo(t2.name)); TailPieces = tailTransformsSorted.ToArray(); ParticleEmitter = sw.transform.FindChild("WormParticleEmitter").GetComponent <SkinnedMeshRenderer> (); ParticleEmitter.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; ParticleEmitter.quality = SkinQuality.Bone1; ParticleEmitter.gameObject.layer = 9; //disabling this for now ParticleEmitter.gameObject.SetActive(false); SkinnedMeshRenderer smr = sw.GetComponentInChildren <SkinnedMeshRenderer> (); smr.sharedMaterials = new Material[] { SandwormMat }; //, BodySandMats [1] }; smr.updateWhenOffscreen = true; startTime = Time.time; startRotations = new Vector3 [TailPieces.Length]; startPositions = new Vector3 [TailPieces.Length]; startParents = new Transform [TailPieces.Length]; for (int i = 0; i < TailPieces.Length; i++) { startPositions [i] = TailPieces [i].localPosition; startRotations [i] = TailPieces [i].localEulerAngles; startParents [i] = TailPieces [i].parent; } Transform wormParent = Worm.parent; Worm.parent = StartNode; Worm.localPosition = Vector3.zero; Worm.localRotation = Quaternion.identity; Worm.parent = wormParent; startParams = new float [TailPieces.Length]; for (int i = 0; i < TailPieces.Length; i++) { startParams [i] = Spline.GetAdjustedTimeAtPoint(TailPieces [i].position, 0.0001f, 0f, 1f, 0.0001f); } baseStartParam = Spline.GetAdjustedTimeAtPoint(Worm.position, 0.0001f, 0f, 1f, 0.0001f); animation = Worm.parent.GetComponent <Animation> (); if (animation == null) { animation = Worm.parent.gameObject.AddComponent <Animation> (); animation.playAutomatically = false; } animation.clip = SandwormAnimationClip; animation.AddClip(SandwormAnimationClip, "SandwormAnimation"); animation.Play("SandwormAnimation"); animation ["SandwormAnimation"].enabled = true; animation ["SandwormAnimation"].normalizedSpeed = 0f; splineAnimation = GetComponent <Animation> (); splineAnimation.Play("SplineAnimation"); splineAnimation ["SplineAnimation"].enabled = true; splineAnimation ["SplineAnimation"].normalizedSpeed = 0f; GameObject swSandBody = GameObject.Find("WormSand"); SkinnedMeshRenderer swSandBodyRenderer = swSandBody.GetComponent <SkinnedMeshRenderer> (); swSandBodyRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; swSandBodyRenderer.useLightProbes = false; swSandBodyRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; swSandBodyRenderer.sharedMaterial = BodySandMats [0]; swSandBodyRenderer.updateWhenOffscreen = true; swSandBodyRenderer.receiveShadows = false; /*Cloth cloth = swSandBodyRenderer.gameObject.AddComponent <Cloth> (); * ClothSkinningCoefficient [] newConstraints = cloth.coefficients; * for (int i = 0; i < newConstraints.Length; i++) { * ClothSkinningCoefficient c = newConstraints [i]; * c.maxDistance = Random.value * 10f; * c.collisionSphereDistance = 0f; * newConstraints [i] = c; * } * cloth.coefficients = newConstraints; * cloth.bendingStiffness = 0.61f; * cloth.stretchingStiffness = 0.61f; * cloth.worldVelocityScale = 600f; * cloth.worldAccelerationScale = 1f; * cloth.randomAcceleration = Vector3.zero;//RandomAcceleration; * cloth.useGravity = true; * cloth.useVirtualParticles = 1f; * cloth.useContinuousCollision = 1f; * cloth.collisionMassScale = 0.5f; * cloth.sleepThreshold = 1f; * cloth.damping = 1f;*/ UnderSprayParent = GameObject.Find("MouthCenter").transform; //GameObject.Find ("Head").transform; Spray = GameObject.Instantiate(SprayPrefab) as GameObject; Spray.transform.parent = GameObject.Find("Mouth1_2").transform; Spray.transform.localPosition = Vector3.zero; }
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; }