Exemplo n.º 1
0
        protected override void AdditionalParams()
        {
            EditorGUILayout.PropertyField(serializedObject.FindProperty("width"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("height"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("heightOffset"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("lengthExtends"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("material"));
            EditorGUILayout.PropertyField(serializedObject.FindProperty("isTrigger"));

            BGEditorUtility.VerticalBox(() =>
            {
                EditorGUILayout.PropertyField(serializedObject.FindProperty("heightAxisMode"));
                if (Collider3DBox.HeightAxisMode == BGCcCollider3DBox.HeightAxisModeEnum.Custom)
                {
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("customHeightAxis"));
                }
                EditorGUILayout.PropertyField(serializedObject.FindProperty("heightAxisRotation"));
            });
            BGEditorUtility.VerticalBox(() =>
            {
                BGEditorUtility.Horizontal(() =>
                {
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("isMeshGenerationOn"));
                    if (!GUILayout.Button(new GUIContent("Remove meshes", "Remove MeshFilter and MeshRenderer components from all child GameObjects with colliders attached"),
                                          GUILayout.Width(120)))
                    {
                        return;
                    }

                    if (Collider3DBox.IsMeshGenerationOn)
                    {
                        BGEditorUtility.Inform("Error", "Please, turn off 'isMeshGenerationOn' toggle first.");
                        return;
                    }

                    var colliders = new List <BoxCollider>();
                    Collider3DBox.FillChildrenColliders(colliders);
                    foreach (var collider in colliders)
                    {
                        var renderer = collider.GetComponent <MeshRenderer>();
                        if (renderer != null)
                        {
                            BGCurve.DestroyIt(renderer);
                        }
                        var filter = collider.GetComponent <MeshFilter>();
                        if (filter != null)
                        {
                            BGCurve.DestroyIt(filter);
                        }
                    }
                });

                if (Collider3DBox.IsMeshGenerationOn)
                {
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("MeshMaterial"));
                }
            });

            BGEditorUtility.VerticalBox(() =>
            {
                EditorGUILayout.PropertyField(serializedObject.FindProperty("generateKinematicRigidbody"));
                if (!Collider3DBox.GenerateKinematicRigidbody)
                {
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("Rigidbody"));
                }
            });


            base.AdditionalParams();
        }
            public Sequence(BGCcCursorChangeLinear changeCursor)
            {
                this.changeCursor = changeCursor;
                var cursor = changeCursor.Cursor;
                var curve  = changeCursor.Curve;

                Curve   = curve;
                started = Time.time;


                if (!Curve.gameObject.activeInHierarchy)
                {
                    return;
                }

                ThrowIf("Stop overflow control is not supported", changeCursor.OverflowControl == BGCcCursorChangeLinear.OverflowControlEnum.Stop);


                var pointsCount = curve.PointsCount;

                ThrowIf("Curve should have at least 2 points.", pointsCount < 2);

                var math = changeCursor.Cursor.Math.Math;

                var sectionIndex  = cursor.CalculateSectionIndex();
                var speed         = changeCursor.CurrentSpeed;
                var speedPositive = speed > 0;

                if (speedPositive)
                {
                    //=================================== Positive speed
                    //first point
                    if (curve.Closed && sectionIndex == pointsCount - 1)
                    {
                        expectedPoints.Add(new ExpectedPoint(0, math.GetDistance() - cursor.Distance, speed, 0));
                    }
                    else if (!curve.Closed && sectionIndex == pointsCount - 2)
                    {
                        expectedPoints.Add(new ExpectedPoint(pointsCount - 1, math.GetDistance() - cursor.Distance, speed, 0));
                    }
                    else
                    {
                        expectedPoints.Add(new ExpectedPoint(sectionIndex + 1, math[sectionIndex + 1].DistanceFromStartToOrigin - cursor.Distance, speed, 0));
                    }

                    //go towards end
                    for (var i = sectionIndex + 2; i < pointsCount; i++)
                    {
                        expectedPoints.Add(new ExpectedPoint(i, math[i - 1].Distance, changeCursor.GetSpeedAtPoint(i - 1), changeCursor.GetDelayAtPoint(i - 1)));
                    }

                    //add last point
                    if (curve.Closed && sectionIndex != pointsCount)
                    {
                        expectedPoints.Add(new ExpectedPoint(0, math[pointsCount - 1].Distance, changeCursor.GetSpeedAtPoint(pointsCount - 1), changeCursor.GetDelayAtPoint(pointsCount - 1)));
                    }


                    if (changeCursor.OverflowControl == BGCcCursorChangeLinear.OverflowControlEnum.PingPong)
                    {
                        if (curve.Closed)
                        {
                            expectedPoints.Add(new ExpectedPoint(pointsCount - 1, math[pointsCount - 1].Distance,
                                                                 changeCursor.GetSpeedAtPoint(pointsCount - 1), changeCursor.GetDelayAtPoint(0)));
                        }

                        //go all the way down
                        for (var i = pointsCount - 2; i >= 0; i--)
                        {
                            expectedPoints.Add(new ExpectedPoint(i, math[i].Distance, changeCursor.GetSpeedAtPoint(i), changeCursor.GetDelayAtPoint(i + 1)));
                        }
                    }
                    else
                    {
                        if (!curve.Closed)
                        {
                            expectedPoints.Add(new ExpectedPoint(0, math[pointsCount - 2].Distance, 0, changeCursor.GetDelayAtPoint(pointsCount - 1)));
                        }
                    }

                    //go up to initial position
                    for (var i = 1; i <= sectionIndex; i++)
                    {
                        expectedPoints.Add(new ExpectedPoint(i, math[i - 1].Distance, changeCursor.GetSpeedAtPoint(i - 1), changeCursor.GetDelayAtPoint(i - 1)));
                    }

                    //last point
                    expectedPoints.Add(new ExpectedPoint(-1, cursor.Distance - math[sectionIndex].DistanceFromStartToOrigin, speed, changeCursor.GetDelayAtPoint(sectionIndex)));
                }
                else
                {
                    //=================================== Negative speed
                    //first point
                    expectedPoints.Add(new ExpectedPoint(sectionIndex, cursor.Distance - math[sectionIndex].DistanceFromStartToOrigin, speed, 0));

                    //go towards start
                    for (var i = sectionIndex - 1; i >= 0; i--)
                    {
                        expectedPoints.Add(new ExpectedPoint(i, math[i].Distance, changeCursor.GetSpeedAtPoint(i), changeCursor.GetDelayAtPoint(i + 1)));
                    }

                    if (changeCursor.OverflowControl == BGCcCursorChangeLinear.OverflowControlEnum.PingPong)
                    {
                        for (var i = 1; i < pointsCount; i++)
                        {
                            expectedPoints.Add(new ExpectedPoint(i, math[i - 1].Distance, changeCursor.GetSpeedAtPoint(i - 1), changeCursor.GetDelayAtPoint(i - 1)));
                        }

                        if (curve.Closed)
                        {
                            expectedPoints.Add(new ExpectedPoint(0, math[pointsCount - 1].Distance, changeCursor.GetSpeedAtPoint(pointsCount - 1), changeCursor.GetDelayAtPoint(pointsCount - 1)));
                            expectedPoints.Add(new ExpectedPoint(pointsCount - 1, math[pointsCount - 1].Distance,
                                                                 changeCursor.GetSpeedAtPoint(pointsCount - 1), changeCursor.GetDelayAtPoint(0)));
                        }
                    }
                    else
                    {
                        if (curve.Closed)
                        {
                            expectedPoints.Add(new ExpectedPoint(pointsCount - 1, math[pointsCount - 1].Distance,
                                                                 changeCursor.GetSpeedAtPoint(pointsCount - 1), changeCursor.GetDelayAtPoint(0)));
                        }
                        else
                        {
                            expectedPoints.Add(new ExpectedPoint(pointsCount - 1, 0, 0, changeCursor.GetDelayAtPoint(0)));
                        }
                    }


                    //go from end to initial section
                    for (var i = pointsCount - 2; i > sectionIndex; i--)
                    {
                        expectedPoints.Add(new ExpectedPoint(i, math[i].Distance, changeCursor.GetSpeedAtPoint(i), changeCursor.GetDelayAtPoint(i + 1)));
                    }

                    //last point
                    expectedPoints.Add(new ExpectedPoint(-1, math[sectionIndex].DistanceFromEndToOrigin - cursor.Distance, changeCursor.GetSpeedAtPoint(sectionIndex),
                                                         changeCursor.GetDelayAtPoint(sectionIndex + 1)));
                }
            }
Exemplo n.º 3
0
 private static BGCurveBaseMath NewMath(BGCurve curve, BGCurveSettings settings)
 {
     return(new BGCurveBaseMath(curve, NewConfig(settings)));
 }
Exemplo n.º 4
0
        public static Func<BGCurvePointI> GetPointProvider(BGCurve.PointsModeEnum pointsMode, BGCurve curve)
        {
            //init provider 
            Func<BGCurvePointI> provider = null;
            switch (pointsMode)
            {
                case BGCurve.PointsModeEnum.Components:
                    provider = () => Undo.AddComponent<BGCurvePointComponent>(curve.gameObject);
                    break;
                case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                case BGCurve.PointsModeEnum.GameObjectsTransform:
                    provider = () =>
                    {
                        var pointGO = new GameObject();
                        var transform = pointGO.transform;
                        transform.parent = curve.transform;
                        transform.localRotation = Quaternion.identity;
                        transform.localPosition = Vector3.zero;
                        transform.localScale = Vector3.one;

                        Undo.RegisterCreatedObjectUndo(pointGO, "Create point");
                        var point = Undo.AddComponent<BGCurvePointGO>(pointGO);
                        return point;
                    };
                    break;
            }

            return provider;
        }
Exemplo n.º 5
0
        public static BGCurvePoint CreatePoint(Vector3 position, BGCurve curve, BGCurvePoint.ControlTypeEnum controlType, int parts, out float distanceToPreviousPoint, out float distanceToNextPoint,
                                               bool ensureNew)
        {
            distanceToPreviousPoint = -1;
            distanceToNextPoint     = -1;

            if (curve.PointsCount == 0)
            {
                //first point
                Vector3 control;
                switch (curve.Mode2D)
                {
                case BGCurve.Mode2DEnum.YZ:
                    control = Vector3.forward;
                    break;

                default:
                    // BGCurve.Mode2DEnum.XY:
                    // BGCurve.Mode2DEnum.Off:
                    // BGCurve.Mode2DEnum.XZ:
                    control = Vector3.right;
                    break;
                }
                return(curve.CreatePointFromLocalPosition(curve.ToLocal(position), controlType, control, -control));
            }

            parts = Mathf.Clamp(parts, 1, 50);

            //we no need no events (maybe check if point was actually added to a curve for events firing?)
            var oldSuppress = curve.SupressEvents;

            curve.SupressEvents = true;

            //create a point with no controls first
            BGCurvePoint newPoint;

            if (ensureNew)
            {
                newPoint = curve.CreatePointFromWorldPosition(position, BGCurvePoint.ControlTypeEnum.Absent);
            }
            else
            {
                if (point == null || point.Curve != curve)
                {
                    point = curve.CreatePointFromWorldPosition(position, BGCurvePoint.ControlTypeEnum.Absent);
                }
                newPoint = point;
                newPoint.PositionWorld      = position;
                newPoint.ControlFirstLocal  = Vector3.zero;
                newPoint.ControlSecondLocal = Vector3.zero;
            }

            if (curve.Mode2DOn)
            {
                curve.Apply2D(newPoint);
            }

            //adjacent points
            var previousPoint = curve[curve.PointsCount - 1];
            var nextPoint     = curve.Closed ? curve[0] : null;

            //direction
            var tangent = BGEditorUtility.CalculateTangent(newPoint, previousPoint, nextPoint, 1 / (float)parts);

            if (tangent.sqrMagnitude < 0.0001f)
            {
                //whatever
                switch (curve.Mode2D)
                {
                case BGCurve.Mode2DEnum.Off:
                case BGCurve.Mode2DEnum.XY:
                case BGCurve.Mode2DEnum.XZ:
                    tangent = Vector3.right;
                    break;

                case BGCurve.Mode2DEnum.YZ:
                    tangent = Vector3.up;
                    break;
                }
            }

            //length
            distanceToPreviousPoint = BGEditorUtility.CalculateDistance(previousPoint, newPoint, parts);
            float minDistance;

            if (nextPoint != null)
            {
                distanceToNextPoint = BGEditorUtility.CalculateDistance(newPoint, nextPoint, parts);
                minDistance         = Math.Min(distanceToPreviousPoint, distanceToNextPoint);
            }
            else
            {
                minDistance = distanceToPreviousPoint;
            }
            var length = minDistance * DistanceToControlMultiplier;


            //we need local tangent for controls
            tangent = curve.ToLocalDirection(tangent);



            newPoint.ControlSecondLocal = tangent * length;

            newPoint.ControlFirstLocal = -newPoint.ControlSecondLocal;


            newPoint.ControlType = controlType;

            curve.SupressEvents = oldSuppress;
            return(newPoint);
        }
Exemplo n.º 6
0
 public static BGCurveBaseMath NewMath(BGCurve curve, BGCurveSettings settings)
 {
     return new BGCurveBaseMath(curve, NewConfig(settings));
 }
Exemplo n.º 7
0
 public static void DeletePoint(BGCurve curve, int index)
 {
     BGPrivateField.Invoke(curve, BGCurve.MethodDeletePoint, new[] {typeof(int), typeof(Action<BGCurvePointI>)}, index, GetPointDestroyer(curve.PointsMode, curve));
 }
Exemplo n.º 8
0
 public static void DrawGizmos(BGCurve curve, GizmoType gizmoType)
 {
     BGCurveEditor.DrawGizmos(curve, gizmoType);
 }
Exemplo n.º 9
0
 protected BGCurveEditorTab(BGCurveEditor editor, SerializedObject serializedObject)
 {
     Editor           = editor;
     Curve            = editor.Curve;
     SerializedObject = serializedObject;
 }
Exemplo n.º 10
0
 private void Awake()
 {
     BgCurve = GetComponent <BGCurve>();
 }
Exemplo n.º 11
0
 public void SetActivePath(BGCurve path)
 {
     activeWorldPath = path;
 }
 protected override void AddPoint(BGCurve curve, Vector3 intersectionPosition, BGCurveSettings settings)
 {
     BGCurveEditor.AddPoint(curve, CreatePoint(curve, settings), pointIndex + 1);
 }
 protected override BGCurvePoint CreatePointForPreview(Vector3 position, BGCurve curve, out float toLast, out float toFirst, BGCurveSettings settings)
 {
     toLast = toFirst = 0;
     return(CreatePoint(curve, settings));
 }
        /// <summary>rebuilds colliders</summary>
        public virtual void UpdateUi()
        {
            var requireGameObjects = RequireGameObjects;

            var workingList = WorkingList;

            if (requireGameObjects)
            {
                //get children colliders for reusing
                FillChildrenColliders(workingList);
            }

            //get positions
            if (LocalSpace && !UseLocal)
            {
                useLocal  = true;
                dataValid = false;
            }

            var positions      = Positions;
            var positionsCount = positions.Count;

            maxExceeded = false;

            var cursor = 0;

            //at least 2 points are needed
            if (positionsCount > 1)
            {
                var count = Mathf.Min(maxNumberOfColliders + 1, positionsCount);
                if (maxNumberOfColliders + 1 < positionsCount)
                {
                    maxExceeded = true;
                }

                if (requireGameObjects)
                {
                    var isPlaying = Application.isPlaying;
                    var baseName  = gameObject.name + " Collider[";
                    var baseLayer = gameObject.layer;
                    for (var i = 1; i < count; i++)
                    {
                        Component collider;

                        //------------ get/create collider
                        if (workingList.Count <= cursor)
                        {
                            if (childPrefab == null)
                            {
                                var go = new GameObject();
                                go.transform.parent = transform;
                                collider            = go.AddComponent <T>();
                            }
                            else
                            {
                                var go = Instantiate(childPrefab, transform);
                                collider = go.GetComponent <T>();
                                if (collider == null)
                                {
                                    collider = go.AddComponent <T>();
                                }
                            }
                        }
                        else
                        {
                            collider = workingList[cursor];
                        }

                        CheckCollider(collider);

                        //------------  assign a layer
                        collider.gameObject.layer = inheritLayer ? baseLayer : layer;


                        //------------  set name (in Editor only)
                        if (!isPlaying)
                        {
                            try
                            {
                                collider.gameObject.name = baseName + (i - 1) + ']';
                            }
                            catch (MissingReferenceException)
                            {
                                return;
                            }
                        }

                        //------------- set up collider
                        SetUpGoCollider((T)collider, positions[i - 1], positions[i]);

                        cursor++;
                    }
                }
                else
                {
                    FillSingleCollider(positions, count);
                }
            }

            if (requireGameObjects)
            {
                //destroy not used GO
                var collidersCount = workingList.Count;
                if (cursor < collidersCount)
                {
                    //temp list is used to properly handle undo operations
                    for (var i = collidersCount - 1; i >= cursor; i--)
                    {
                        var collider = workingList[i];
                        workingList.RemoveAt(i);

                        BGCurve.DestroyIt(collider.gameObject);
                    }
                }

                workingList.Clear();
            }
        }
        //===============================================================================================
        //                                                    Private methods
        //===============================================================================================
        protected override void SetUpGoCollider(BoxCollider collider, Vector3 from, Vector3 to)
        {
            var dir = to - from;

            //transform position
            collider.transform.position = from;
            //transform  rotation
            Vector3 upDirection;

            switch (HeightAxisMode)
            {
            case HeightAxisModeEnum.Y:
                upDirection = Vector3.up;
                break;

            case HeightAxisModeEnum.X:
                upDirection = Vector3.right;
                break;

            case HeightAxisModeEnum.Z:
                upDirection = Vector3.forward;
                break;

            case HeightAxisModeEnum.Custom:
                upDirection = customHeightAxis;
                if (upDirection == Vector3.zero)
                {
                    upDirection = Vector3.up;
                }
                break;

            default:
                throw new ArgumentOutOfRangeException("HeightAxisMode");
            }
            collider.transform.rotation = Quaternion.LookRotation(dir, upDirection);
            collider.transform.Rotate(Vector3.forward, heightAxisRotation);

            //colliders center and size
            var colliderLength = dir.magnitude + LengthExtends;

            collider.center = new Vector3(0, Height * .5f + heightOffset, colliderLength * .5f - LengthExtends * .5f);
            collider.size   = new Vector3(width, Height, colliderLength);

            //set is trigger
            collider.isTrigger = IsTrigger;
            //set material
            collider.material = Material;

            //generate mesh along with colliders
            if (isMeshGenerationOn)
            {
                var offset = collider.transform.InverseTransformDirection(dir) * .5f + Vector3.up * (heightOffset + Height * .5f);
                GenerateMesh(collider, offset, width, Height, colliderLength);
            }

            //rigidbody
            var colliderRigidbody = collider.gameObject.GetComponent <Rigidbody>();

            if (generateKinematicRigidbody || Rigidbody != null)
            {
                if (colliderRigidbody == null)
                {
                    colliderRigidbody = collider.gameObject.AddComponent <Rigidbody>();
                }
                if (generateKinematicRigidbody)
                {
                    colliderRigidbody.isKinematic = true;
                }
                else
                {
                    colliderRigidbody.mass                   = Rigidbody.mass;
                    colliderRigidbody.drag                   = Rigidbody.drag;
                    colliderRigidbody.angularDrag            = Rigidbody.angularDrag;
                    colliderRigidbody.useGravity             = Rigidbody.useGravity;
                    colliderRigidbody.isKinematic            = Rigidbody.isKinematic;
                    colliderRigidbody.interpolation          = Rigidbody.interpolation;
                    colliderRigidbody.collisionDetectionMode = Rigidbody.collisionDetectionMode;
                    colliderRigidbody.constraints            = Rigidbody.constraints;
                }
            }
            else if (colliderRigidbody != null)
            {
                BGCurve.DestroyIt(colliderRigidbody);
            }
        }
Exemplo n.º 16
0
 public static BGCurveSettings GetSettings(BGCurve curve)
 {
     return(Get <BGCurveSettings>(curve, "settings"));
 }
Exemplo n.º 17
0
        // Use this for initialization
        private void Start()
        {
            //init components
            curve        = gameObject.AddComponent <BGCurve>();
            curve.Closed = true;
            math         = gameObject.AddComponent <BGCcMath>();
            gameObject.AddComponent <BGCcVisualizationLineRenderer>();
            var lineRenderer = gameObject.GetComponent <LineRenderer>();

            lineRenderer.sharedMaterial = LineRendererMaterial;
            var color = new Color(.2f, .2f, .2f, 1f);

#if UNITY_5_5 || UNITY_5_6 || UNITY_5_6_OR_NEWER
            lineRenderer.startWidth = lineRenderer.endWidth = .03f;
            lineRenderer.startColor = lineRenderer.endColor = color;
#else
            lineRenderer.SetWidth(.03f, .03f);
            lineRenderer.SetColors(color, color);
#endif
            math.SectionParts = NumberOfSplits;

            //create curve's points
            for (var i = 0; i < NumberOfCurvePoints; i++)
            {
                var controlRandom = Random.Range(0, 3);
                var controlType   = BGCurvePoint.ControlTypeEnum.Absent;
                switch (controlRandom)
                {
                case 1:
                    controlType = BGCurvePoint.ControlTypeEnum.BezierIndependant;
                    break;

                case 2:
                    controlType = BGCurvePoint.ControlTypeEnum.BezierSymmetrical;
                    break;
                }
                curve.AddPoint(new BGCurvePoint(curve,
                                                Vector3.zero,
                                                controlType,
                                                RandomVector() * .3f,
                                                RandomVector() * .3f));
            }

            //init arrays
            oldPointPos      = new Vector3[NumberOfPointsToSeek];
            newPointPos      = new Vector3[NumberOfPointsToSeek];
            oldCurvePointPos = new Vector3[NumberOfCurvePoints];
            newCurvePointPos = new Vector3[NumberOfCurvePoints];

            InitArray(newCurvePointPos, oldCurvePointPos);
            InitArray(newPointPos, oldPointPos);

            //create objects
            objects = new GameObject[NumberOfPointsToSeek];
            for (var i = 0; i < NumberOfPointsToSeek; i++)
            {
                var clone = Instantiate(PointIndicator);
                clone.transform.parent = transform;
                objects[i]             = clone;
            }
            PointIndicator.SetActive(false);

            //init cycle
            InitCycle();
        }
Exemplo n.º 18
0
 //--------------------------------------- Settings
 public static void SetSettings(BGCurve curve, BGCurveSettings settings)
 {
     Set(curve, "settings", settings);
 }
Exemplo n.º 19
0
 public static void AddPoint(BGCurve curve, BGCurvePoint point, int index)
 {
     BGPrivateField.Invoke(curve, BGCurve.MethodAddPoint, point, index, GetPointProvider(curve.PointsMode, curve));
 }
Exemplo n.º 20
0
 public new static void DrawGizmos(BGCurve curve, GizmoType gizmoType)
 {
     BGCurvePointGOEditor.DrawGizmos(curve, gizmoType);
 }
Exemplo n.º 21
0
 public static void DeletePoints(BGCurve curve, BGCurvePointI[] points)
 {
     BGPrivateField.Invoke(curve, BGCurve.MethodDeletePoint, new[] {typeof(BGCurvePointI[]), typeof(Action<BGCurvePointI>)}, points, GetPointDestroyer(curve.PointsMode, curve));
 }
Exemplo n.º 22
0
 protected void Start()
 {
     BgCurve = BgCurve ?? GetComponent <BGCurve>();
     OnPathUpdate?.Invoke();
 }
Exemplo n.º 23
0
        public static Action<BGCurvePointI> GetPointDestroyer(BGCurve.PointsModeEnum pointsMode, BGCurve curve)
        {
            //init destroyer
            Action<BGCurvePointI> destroyer = null;
            switch (pointsMode)
            {
                case BGCurve.PointsModeEnum.Components:
                    destroyer = point => Undo.DestroyObjectImmediate((UnityEngine.Object) point);
                    break;
                case BGCurve.PointsModeEnum.GameObjectsNoTransform:
                case BGCurve.PointsModeEnum.GameObjectsTransform:
                    destroyer = point => Undo.DestroyObjectImmediate(((MonoBehaviour) point).gameObject);
                    break;
            }

            return destroyer;
        }
Exemplo n.º 24
0
            public Tree(BGCurve curve) : base(new Config(2, 8, 0, 2, 0))
            {
                Curve = curve;

                whiteTexture = BGEditorUtility.Texture1X1(Color.white);
            }
Exemplo n.º 25
0
        protected override void SetUpGoCollider(BoxCollider2D collider, Vector3 from, Vector3 to)
        {
            var dir = to - from;

            var angle = Vector3.Angle(Vector3.right, dir);

            angle = dir.y < 0 ? 360 - angle : angle;


            collider.transform.rotation = Quaternion.Euler(0, 0, angle);
            collider.transform.position = from;

            var colliderLength = dir.magnitude + LengthExtends;

            collider.offset = new Vector3(colliderLength * .5f - LengthExtends * .5f, heightOffset);
            collider.size   = new Vector2(colliderLength, height);

            collider.isTrigger = IsTrigger;

            collider.sharedMaterial = Material;

            collider.usedByEffector = usedByEffector;

            //rigidbody
            var colliderRigidbody = collider.gameObject.GetComponent <Rigidbody2D>();

            if (generateKinematicRigidbody || Rigidbody != null)
            {
                if (colliderRigidbody == null)
                {
                    colliderRigidbody = collider.gameObject.AddComponent <Rigidbody2D>();
                }
                if (generateKinematicRigidbody)
                {
                    colliderRigidbody.isKinematic = true;
                }
                else
                {
                    colliderRigidbody.mass                   = Rigidbody.mass;
                    colliderRigidbody.drag                   = Rigidbody.drag;
                    colliderRigidbody.angularDrag            = Rigidbody.angularDrag;
                    colliderRigidbody.gravityScale           = Rigidbody.gravityScale;
                    colliderRigidbody.isKinematic            = Rigidbody.isKinematic;
                    colliderRigidbody.interpolation          = Rigidbody.interpolation;
                    colliderRigidbody.sleepMode              = Rigidbody.sleepMode;
                    colliderRigidbody.collisionDetectionMode = Rigidbody.collisionDetectionMode;
                    colliderRigidbody.constraints            = Rigidbody.constraints;
                }
            }
            else if (colliderRigidbody != null)
            {
                BGCurve.DestroyIt(colliderRigidbody);
            }

#if UNITY_5_6_OR_NEWER
            if (usedByComposite)
            {
                collider.usedByComposite = true;
            }
#endif
        }
        private void InspectorTopSection()
        {
            if (Curve.PointsCount == 0)
            {
                EditorGUILayout.HelpBox(
                    "1) Ctrl + LeftClick in scene view to add a point and snap it to  "
                    + "\r\n    a) 3D mode: mesh with collider"
                    + "\r\n    b) 2D mode: curve's 2D plane."
                    + "\r\n"
                    + "\r\n2) Ctrl + Shift + LeftClick in Scene View to add a point unconditionally at some distance, specified in the settings."
                    + "\r\n"
                    + "\r\n3) Hold control over existing point or selection to access Scene View menu"
                    + "\r\n"
                    + "\r\n4) Hold shift + drag to use rectangular selection in Scene View"
                    , MessageType.Info);
            }


            try
            {
                // Curve's block
                BGEditorUtility.VerticalBox(() =>
                {
                    //closed
                    EditorGUILayout.PropertyField(closedProperty);


                    //point's store mode
                    BGEditorUtility.Horizontal(() =>
                    {
                        EditorGUILayout.PropertyField(pointsModeProperty);

                        BGEditorUtility.DisableGui(() =>
                        {
                            BGEditorUtility.Assign(ref syncContent, () => new GUIContent("Sync", "Sort points Game Objects and update names"));

                            if (!GUILayout.Button(syncContent))
                            {
                                return;
                            }

                            BGPrivateField.Invoke(Curve, BGCurve.MethodSetPointsNames);
                        }, !BGCurve.IsGoMode(Curve.PointsMode));
                    });


                    //2D mode
                    BGEditorUtility.Horizontal(() =>
                    {
                        EditorGUILayout.PropertyField(mode2DProperty);
                        BGEditorUtility.DisableGui(() =>
                        {
                            if (!GUILayout.Button("Apply", GUI.skin.button, GUILayout.Width(80)))
                            {
                                return;
                            }

                            Curve.FireBeforeChange(BGCurve.Event2D);
                            Curve.Apply2D(Curve.Mode2D);
                            Curve.FireChange(BGCurveChangedArgs.GetInstance(Curve, BGCurveChangedArgs.ChangeTypeEnum.Points, BGCurve.Event2D));
                        }, mode2DProperty.enumValueIndex == 0);
                    });

                    //snapping
                    BGEditorUtility.VerticalBox(() =>
                    {
                        BGEditorUtility.Horizontal(() =>
                        {
                            EditorGUILayout.PropertyField(snapTypeProperty);

                            BGEditorUtility.DisableGui(() =>
                            {
                                if (!GUILayout.Button("Apply", GUI.skin.button, GUILayout.Width(80)))
                                {
                                    return;
                                }

                                Curve.FireBeforeChange(BGCurve.EventSnapType);
                                Curve.ApplySnapping();
                                Curve.FireChange(BGCurveChangedArgs.GetInstance(Curve, BGCurveChangedArgs.ChangeTypeEnum.Snap, BGCurve.EventSnapType));
                            }, snapTypeProperty.enumValueIndex == 0);
                        });

                        if (snapTypeProperty.enumValueIndex == 0)
                        {
                            return;
                        }

                        EditorGUILayout.PropertyField(snapAxisProperty);
                        EditorGUILayout.PropertyField(snapDistanceProperty);
                        EditorGUILayout.PropertyField(snapTriggerInteractionProperty);
                        EditorGUILayout.PropertyField(snapToBackFacesProperty);

                        BGEditorUtility.LayerMaskField("Snap Layer Mask", Curve.SnapLayerMask, i =>
                        {
                            Curve.FireBeforeChange(BGCurve.EventSnapTrigger);
                            Curve.SnapLayerMask = i;
                            Curve.ApplySnapping();
                            Curve.FireChange(BGCurveChangedArgs.GetInstance(Curve, BGCurveChangedArgs.ChangeTypeEnum.Snap, BGCurve.EventSnapTrigger));
                        });
                    });

                    //event mode
                    EditorGUILayout.PropertyField(eventModeProperty);

                    //force update
                    EditorGUILayout.PropertyField(forceChangedEventModeProperty);

                    //convert control type
                    BGEditorUtility.Horizontal(() =>
                    {
                        EditorGUILayout.PropertyField(controlTypeProperty);

                        if (!BGEditorUtility.ButtonWithIcon(convertAll2D, "Convert control types for all existing points ", 44))
                        {
                            return;
                        }

                        var settings = Settings;

                        foreach (var point in Curve.Points.Where(point => point.ControlType != settings.ControlType))
                        {
                            point.ControlType = settings.ControlType;
                        }
                    });
                });
            }
            catch (BGEditorUtility.ExitException)
            {
                GUIUtility.ExitGUI();
            }
        }
Exemplo n.º 27
0
            public static void OnSceneGui(Plane[] frustum, BGCurve curve, BGCurveSettings settings, BGCurveEditorPointsSelection editorSelection)
            {
                Array.Resize(ref visiblePoints, curve.PointsCount);
                curve.ForEach((point, i, count) => visiblePoints[i] = GeometryUtility.TestPlanesAABB(frustum, new Bounds(point.PositionWorld, Vector3.one)));


                var fieldsCount       = curve.FieldsCount;
                var fields            = curve.Fields;
                var showPointsNumbers = settings.ShowLabels;

                var fieldsWithHandlesCount = 0;
                var fieldsWithLabelCount   = 0;

                if (fieldsCount > 0)
                {
                    fieldsWithHandlesCount = fields.Count(FieldWithHandlesPredicate);
                    if (fieldsWithHandlesCount > 0)
                    {
                        Array.Resize(ref handlesColor, fieldsWithHandlesCount);
                        var cursor = 0;
                        for (var i = 0; i < fieldsCount; i++)
                        {
                            var f = fields[i];
                            if (!FieldWithHandlesPredicate(f))
                            {
                                continue;
                            }

                            if (FieldWithLabelPredicate(f))
                            {
                                fieldsWithLabelCount++;
                            }
                            handlesColor[cursor++] = BGPrivateField.GetHandlesColor(f);
                        }
                    }
                }

                // nothing to show
                if (!showPointsNumbers && fieldsWithHandlesCount == 0)
                {
                    return;
                }


                if (fieldsWithHandlesCount > 0)
                {
                    //not a label
                    curve.ForEach((point, i, length) =>
                    {
                        if (!visiblePoints[i] || !settings.RestrictGizmozSettings.IsShowing(i))
                        {
                            return;
                        }

                        var pos = point.PositionWorld;

                        var quanterionShown = false;
                        var fieldCursor     = 0;
                        for (var j = 0; j < fields.Length; j++)
                        {
                            var field       = fields[j];
                            var handlesType = (HandlesType)BGPrivateField.GetHandlesType(field);

                            if (handlesType == 0)
                            {
                                continue;
                            }

                            if (handlesType == HandlesType.Label)
                            {
                                fieldCursor++;
                                continue;
                            }

                            var color = handlesColor[fieldCursor++];
                            switch (handlesType)
                            {
                            case HandlesType.DistanceFromPoint:
                                BGEditorUtility.SwapHandlesColor(color, () =>
                                {
#if UNITY_5_6_OR_NEWER
                                    Handles.CircleHandleCap(0, pos, Quaternion.LookRotation(SceneView.currentDrawingSceneView.camera.transform.position - pos),
                                                            point.GetField <float>(field.FieldName), EventType.Repaint);
#else
                                    Handles.CircleCap(0, pos, Quaternion.LookRotation(SceneView.currentDrawingSceneView.camera.transform.position - pos),
                                                      point.GetField <float>(field.FieldName));
#endif
                                }
                                                                 );
                                break;

                            case HandlesType.BoundsAroundPoint:
                                Bounds bounds;
                                switch (field.Type)
                                {
                                case BGCurvePointField.TypeEnum.Bounds:
                                    bounds        = point.GetField <Bounds>(field.FieldName);
                                    bounds.center = pos;
                                    break;

                                default:
                                    //vector3
                                    var vector3 = point.GetField <Vector3>(field.FieldName);
                                    bounds      = new Bounds(pos, vector3);
                                    break;
                                }
                                BGEditorUtility.DrawBound(bounds, new Color(color.r, color.g, color.b, 0.05f), color);
                                break;

                            case HandlesType.Bounds:
                                var boundsValue = point.GetField <Bounds>(field.FieldName);
                                if (boundsValue.extents != Vector3.zero)
                                {
                                    BGEditorUtility.DrawBound(boundsValue, new Color(color.r, color.g, color.b, 0.05f), color);
                                    BGEditorUtility.SwapHandlesColor(color, () => Handles.DrawDottedLine(boundsValue.center, pos, 4));
                                }
                                break;

                            case HandlesType.Direction:
                                var vector3Value = point.GetField <Vector3>(field.FieldName);
                                if (vector3Value != Vector3.zero)
                                {
                                    BGEditorUtility.SwapHandlesColor(color, () =>
                                    {
#if UNITY_5_6_OR_NEWER
                                        Handles.ArrowHandleCap(0, pos, Quaternion.LookRotation(vector3Value),
                                                               vector3Value.magnitude, EventType.Repaint);
#else
                                        Handles.ArrowCap(0, pos, Quaternion.LookRotation(vector3Value), vector3Value.magnitude);
#endif
                                    });
                                }
                                break;

                            case HandlesType.Rotation:
                                if (quanterionShown)
                                {
                                    break;
                                }

                                quanterionShown = true;

                                var quaternionValue = point.GetField <Quaternion>(field.FieldName);
                                if (quaternionValue.x < BGCurve.Epsilon && quaternionValue.y < BGCurve.Epsilon && quaternionValue.z < BGCurve.Epsilon && quaternionValue.w < BGCurve.Epsilon)
                                {
                                    quaternionValue = Quaternion.identity;
                                }

                                var newValue = Handles.RotationHandle(quaternionValue, pos);
                                point.SetField(field.FieldName, newValue);


                                BGEditorUtility.SwapHandlesColor(color, () =>
                                {
                                    var rotated = newValue * Vector3.forward * BGEditorUtility.GetHandleSize(pos, 2);
                                    var toPos   = pos + rotated;
#if UNITY_5_6_OR_NEWER
                                    Handles.ArrowHandleCap(0, toPos, newValue, 1, EventType.Repaint);
#else
                                    Handles.ArrowCap(0, toPos, newValue, 1);
#endif
                                    Handles.DrawDottedLine(pos, toPos, 10);
                                });
                                break;

                            case HandlesType.Link:
                                switch (field.Type)
                                {
                                case BGCurvePointField.TypeEnum.GameObject:
                                    var go = point.GetField <GameObject>(field.FieldName);
                                    if (go != null)
                                    {
                                        BGEditorUtility.SwapHandlesColor(color, () => Handles.DrawDottedLine(go.transform.position, pos, 4));
                                    }
                                    break;

                                case BGCurvePointField.TypeEnum.BGCurve:
                                    var bgCurve = point.GetField <BGCurve>(field.FieldName);
                                    if (bgCurve != null)
                                    {
                                        BGEditorUtility.SwapHandlesColor(color, () => Handles.DrawDottedLine(bgCurve.transform.position, pos, 4));
                                    }
                                    break;

                                case BGCurvePointField.TypeEnum.BGCurvePointComponent:
                                    var pointComponent = point.GetField <BGCurvePointComponent>(field.FieldName);
                                    if (pointComponent != null)
                                    {
                                        BGEditorUtility.SwapHandlesColor(color, () => Handles.DrawDottedLine(pointComponent.PositionWorld, pos, 4));
                                    }
                                    break;

                                case BGCurvePointField.TypeEnum.BGCurvePointGO:
                                    var pointGO = point.GetField <BGCurvePointGO>(field.FieldName);
                                    if (pointGO != null)
                                    {
                                        BGEditorUtility.SwapHandlesColor(color, () => Handles.DrawDottedLine(pointGO.PositionWorld, pos, 4));
                                    }
                                    break;
                                }
                                break;
                            }
                        }
                    });
                }

                // nothing more to show
                if (!showPointsNumbers && fieldsWithLabelCount == 0)
                {
                    return;
                }

                //=============================== Labels

                //styles
                var labelColor    = settings.LabelColor;
                var selectedColor = settings.LabelColorSelected;
                var backColor     = BGCurveSettingsForEditor.I.Get <Color32>(BGCurveSettingsForEditor.ColorForLabelBackgroundKey);

                if (labelStyle == null || labelStyle.normal.textColor != labelColor || labelStyle.normal.background == null ||
                    latestLabelBackColor.r != backColor.r || latestLabelBackColor.g != backColor.g || latestLabelBackColor.b != backColor.b || latestLabelBackColor.a != backColor.a)
                {
                    latestLabelBackColor = backColor;
                    labelStyle           = new GUIStyle("Label")
                    {
                        richText = true,
                        border   = new RectOffset(2, 2, 2, 2),
                        clipping = TextClipping.Overflow,
                        wordWrap = false,
                        normal   =
                        {
                            background = BGEditorUtility.TextureWithBorder(8, 1, backColor, new Color32(backColor.r, backColor.g, backColor.b, 255)),
                            textColor  = labelColor
                        }
                    };

                    selectedlabelStyle = new GUIStyle(labelStyle)
                    {
                        normal =
                        {
                            background = BGEditorUtility.TextureWithBorder(8, 1, new Color(selectedColor.r, selectedColor.g, selectedColor.b, .1f), selectedColor),
                            textColor  = selectedColor
                        }
                    };
                }


                curve.ForEach((point, i, length) =>
                {
                    if (!visiblePoints[i])
                    {
                        return;
                    }

                    var pos = point.PositionWorld;

                    var style = !editorSelection.Contains(point) ? labelStyle : selectedlabelStyle;
                    var text  = "";

                    //point numbers and pos
                    if (showPointsNumbers)
                    {
                        text += "# : " + i + "\r\n";
                        if (settings.ShowPositions)
                        {
                            text += "P : " + pos + "\r\n";
                        }
                    }

                    //fields
                    if (fieldsWithLabelCount > 0)
                    {
                        for (var j = 0; j < fieldsCount; j++)
                        {
                            var field = fields[j];
                            if (!FieldWithHandlesPredicate(field) || !FieldWithLabelPredicate(field))
                            {
                                continue;
                            }

                            text += BGEditorUtility.ColorIt(field.FieldName + " : " + point.GetField(field.FieldName, BGCurvePoint.FieldTypes.GetType(field.Type)),
                                                            BGEditorUtility.ToHex(BGPrivateField.GetHandlesColor(field))) + "\r\n";
                        }
                    }

                    var normalized  = (SceneView.currentDrawingSceneView.camera.transform.position - pos).normalized;
                    var handleSize  = BGEditorUtility.GetHandleSize(pos, .25f);
                    var shiftLeft   = -Vector3.Cross(normalized, Vector3.up);
                    var shiftBottom = Vector3.Cross(normalized, Vector3.right) * .3f;
                    Handles.Label(pos + handleSize * shiftLeft + handleSize * shiftBottom, text.Substring(0, text.Length - 2), style);
                });
            }
Exemplo n.º 28
0
        /// <summary>rebuilds colliders</summary>
        public virtual void UpdateUi()
        {
            var requireGameObjects = RequireGameObjects;

            var workingList = WorkingList;

            if (requireGameObjects)
            {
                //get children colliders for reusing
                FillChildrenColliders(workingList);
            }

            //get positions
            if (LocalSpace && !UseLocal)
            {
                useLocal  = true;
                dataValid = false;
            }
            var positions      = Positions;
            var positionsCount = positions.Count;

            maxExceeded = false;

            var cursor = 0;

            //at least 2 points are needed
            if (positionsCount > 1)
            {
                var count = Mathf.Min(maxNumberOfColliders + 1, positionsCount);
                if (maxNumberOfColliders + 1 < positionsCount)
                {
                    maxExceeded = true;
                }

                if (requireGameObjects)
                {
                    for (var i = 1; i < count; i++)
                    {
                        Component collider;

                        //get/create collider
                        if (workingList.Count <= cursor)
                        {
                            var go = new GameObject();
                            go.transform.parent = transform;
                            collider            = go.AddComponent <T>();
                        }
                        else
                        {
                            collider = workingList[cursor];
                        }

                        CheckCollider(collider);

                        var colliderGameObject = collider.gameObject;
                        //set name
                        try
                        {
                            colliderGameObject.name = gameObject.name + " Collider[" + (i - 1) + "]";
                        }
                        catch (MissingReferenceException)
                        {
                            return;
                        }


                        //set up coordinates
                        var from = positions[i - 1];
                        var to   = positions[i];

                        SetUpGoCollider((T)collider, from, to);

                        cursor++;
                    }
                }
                else
                {
                    FillSingleCollider(positions, count);
                }
            }

            if (requireGameObjects)
            {
                //destroy not used GO
                var collidersCount = workingList.Count;
                if (cursor < collidersCount)
                {
                    //temp list is used to properly handle undo operations
                    for (var i = collidersCount - 1; i >= cursor; i--)
                    {
                        var collider = workingList[i];
                        workingList.RemoveAt(i);

                        BGCurve.DestroyIt(collider.gameObject);
                    }
                }
                workingList.Clear();
            }
        }
Exemplo n.º 29
0
        protected void OnEnable()
        {
            Curve            = (BGCurve)target;
            CurrentCurve     = Curve;
            transformMonitor = new BGTransformMonitor(Curve);

            var settings = BGPrivateField.GetSettings(Curve);


            //painter and math
            if (curve2Painter.ContainsKey(Curve))
            {
                var painterGizmo = curve2Painter[Curve];
                if (painterGizmo.Math != null)
                {
                    painterGizmo.Math.Dispose();
                }
                curve2Painter.Remove(Curve);
            }

            Math = NewMath(Curve, settings);
            CurrentGizmoPainter = new BGCurvePainterGizmo(Math);


            //overlay
            BGEditorUtility.Assign(ref OverlayMessage, () => new BGOverlayMessage());

            //probably we do not need it for play mode.. probably
            if (!Application.isPlaying)
            {
                //they are not persistent
                Curve.EventMode     = BGCurve.EventModeEnum.Immediate;
                Curve.BeforeChange += BeforeCurveChange;
                Curve.Changed      += CurveChanged;
            }


            if (!settings.Existing)
            {
                //newly created
                settings.Existing = true;

                var defaultSettings = BGCurveSettingsOperations.LoadDefault();
                if (defaultSettings != null)
                {
                    BGPrivateField.SetSettings(Curve, defaultSettings);
                }
            }

            //load textures
            BGEditorUtility.Assign(ref headerTexture, () => BGEditorUtility.LoadTexture2D(BGEditorUtility.Image.BGCurveLogo123));
            stickerTextureOk      = BGEditorUtility.Texture1X1(new Color32(46, 143, 168, 255));
            stickerTextureError   = BGEditorUtility.Texture1X1(new Color32(255, 0, 0, 255));
            stickerTextureWarning = BGEditorUtility.Texture1X1(new Color32(255, 206, 92, 255));
            stickerTextureActive  = BGEditorUtility.Texture1X1(new Color32(44, 160, 90, 255));

            // editors
            editors = GetEditors();

            headers = editors.Select(editor => editor.Header2D).ToArray();


            foreach (var editor in editors)
            {
                editor.OnEnable();
            }

            //do it every frame
            EditorApplication.update -= OverlayMessage.Check;
            EditorApplication.update += OverlayMessage.Check;

            Undo.undoRedoPerformed -= InternalOnUndoRedo;
            Undo.undoRedoPerformed += InternalOnUndoRedo;
        }
Exemplo n.º 30
0
 //default implementation adds a point to the spline's end
 protected virtual void AddPoint(BGCurve curve, Vector3 intersectionPosition, BGCurveSettings settings)
 {
     BGCurveEditor.AddPoint(curve,
                            BGNewPointPositionManager.CreatePoint(intersectionPosition, curve, settings.ControlType, settings.Sections, true),
                            curve.PointsCount);
 }