public bool GetState(InputDevice inputDevice)
 {
     return(!Mathf.Approximately(GetValue(inputDevice), 0.0f));
 }
Example #2
0
 public static float Remainder(float _numerator, float _denominator)
 {
     return(Mathf.Approximately(_denominator, 0) ? 0 : (_numerator % _denominator));
 }
Example #3
0
    void Update()
    {
        if (!gameManager.roundStarted)
        {
            return;
        }


        if (this.isOnSurface > 1)
        {
            this.isWalking = false;
            this.movement  = Vector3.zero;

            float horiInput = Input.GetAxisRaw("Horizontal");
            float vertInput = Input.GetAxisRaw("Vertical");

            if (!Mathf.Approximately(horiInput, 0) || !Mathf.Approximately(vertInput, 0))
            {
                this.gameObject.transform.up
                    = new Vector3(horiInput * speed * Time.deltaTime,
                                  vertInput * speed * Time.deltaTime,
                                  0.0f);
            }

            // I had the bright idea of raycasting three times instead of making a collider
            // If you stumble on this code, learn from my stupidity and this better
            // - Miguel
            RaycastHit2D hit1 = Physics2D.Raycast(this.transform.position + this.transform.up * 0.5f + this.transform.transform.right * 0.1f,
                                                  this.transform.up,
                                                  0.5f,
                                                  this.layerMask);
            RaycastHit2D hit2 = Physics2D.Raycast(this.transform.position + this.transform.up * 0.5f - this.transform.transform.right * 0.1f,
                                                  this.transform.up,
                                                  0.5f,
                                                  this.layerMask);
            RaycastHit2D hit3 = Physics2D.Raycast(this.transform.position + this.transform.up * 0.5f,
                                                  this.transform.up,
                                                  0.5f,
                                                  this.layerMask);
            if (!Mathf.Approximately(horiInput, 0))
            {
                this.movement += new Vector3(horiInput * speed * Time.deltaTime, 0.0f, 0.0f);
                this.isWalking = true;
            }
            if (!Mathf.Approximately(vertInput, 0))
            {
                if ((hit1.collider != null || hit2.collider != null) && vertInput > 0.0f)
                {
                    this.movement += new Vector3(0.0f, vertInput * speed * Time.deltaTime, 0.0f);
                }
                else if (vertInput < 0.0f)
                {
                    this.movement += new Vector3(0.0f, vertInput * speed * Time.deltaTime, 0.0f);
                }
                this.isWalking = true;
            }
            if (Input.GetButton("Jump") && canJump)
            {
                canJump        = false;
                this.isWalking = false;
                this.animator.ResetTrigger("Idle");
                this.animator.ResetTrigger("Walk");
                this.animator.SetTrigger("Jump");
                this.movement += new Vector3(0.0f, vertInput * speed * Time.deltaTime, 0.0f);
                this.GetComponent <Rigidbody2D>().velocity = this.movement * jump;
                this.audioSource.PlayOneShot(this.jumpSound);
                if (!makingWeb)
                {
                    this.startingWeb = true;
                    this.web         = Instantiate(this.webOriginal);
                }


                StartCoroutine("CooldownJump");
            }

            if (this.isWalking)
            {
                this.animator.ResetTrigger("Idle");
                this.animator.SetTrigger("Walk");
            }
            else
            {
                this.animator.ResetTrigger("Walk");
                this.animator.SetTrigger("Idle");
            }

            if (this.isWalking)
            {
                this.gameObject.transform.position += this.movement;
            }

            /* this.gameObject.transform.up = this.movement; */
        }
        else
        {
            this.GetComponent <Rigidbody2D>().gravityScale = 1;
        }

        if (this.makingWeb)
        {
            this.EndWeb(this.gameObject.transform.GetChild(0).transform.position);
        }
    }
 private bool LineContainsPoint(Point point, Pair <Point, Point> line)
 {
     return(Mathf.Approximately(Point.Distance(line.First, point) + Point.Distance(line.Second, point), Point.Distance(line.First, line.Second)));
 }
        private void PaintControls()
        {
            float areaWidth  = PreferencesWindow.WIN_MIN_WIDTH - PreferencesWindow.SIDEBAR_WIDTH;
            float areaHeight = PreferencesWindow.WIN_MIN_HEIGHT - EditorGUIUtility.singleLineHeight;

            Rect btnPrevRect = new Rect(
                areaWidth / 2.0f - (CONTROL_DOT_WIDTH * this.pages.Length / 2.0f) - CONTROL_BTN_WIDTH,
                areaHeight - EditorGUIUtility.singleLineHeight - CONTROL_MARGIN_BOTTOM,
                CONTROL_BTN_WIDTH,
                EditorGUIUtility.singleLineHeight
                );

            Rect btnNextRect = new Rect(
                areaWidth / 2.0f + (CONTROL_DOT_WIDTH * this.pages.Length / 2.0f),
                areaHeight - EditorGUIUtility.singleLineHeight - CONTROL_MARGIN_BOTTOM,
                CONTROL_BTN_WIDTH,
                EditorGUIUtility.singleLineHeight
                );

            EditorGUI.BeginDisabledGroup(Mathf.Approximately(this.animPagesIndex.target, 0.0f));
            if (GUI.Button(btnPrevRect, "Previous", EditorStyles.miniButtonLeft))
            {
                float target = this.animPagesIndex.target - 1.0f;
                if (target < 0.0f)
                {
                    target = 0.0f;
                }
                this.animPagesIndex.target = target;
            }
            EditorGUI.EndDisabledGroup();

            for (int i = 0; i < this.pages.Length; ++i)
            {
                Rect btnDot = new Rect(
                    areaWidth / 2.0f - (CONTROL_DOT_WIDTH * this.pages.Length / 2.0f) + (CONTROL_DOT_WIDTH * i),
                    areaHeight - EditorGUIUtility.singleLineHeight - CONTROL_MARGIN_BOTTOM,
                    CONTROL_DOT_WIDTH,
                    EditorGUIUtility.singleLineHeight
                    );

                GUIStyle dotStyle = (Mathf.Approximately(this.animPagesIndex.target, (float)i)
                                        ? this.controlDotActive
                                        : this.controlDotNormal
                                     );

                if (GUI.Button(btnDot, (i + 1).ToString(), dotStyle))
                {
                    this.animPagesIndex.target = (float)i;
                }
            }

            EditorGUI.BeginDisabledGroup(Mathf.Approximately(this.animPagesIndex.target, this.pages.Length - 1.0f));
            if (GUI.Button(btnNextRect, "Next", EditorStyles.miniButtonRight))
            {
                float target = this.animPagesIndex.target + 1.0f;
                if (target > this.pages.Length - 1.0f)
                {
                    target = this.pages.Length - 1.0f;
                }
                this.animPagesIndex.target = target;
            }
            EditorGUI.EndDisabledGroup();
        }
Example #6
0
    void UpdateBarValue()
    {
        if (effectBurn)
        {
            if (effectSmoothChange)
            {
                // in burn mode smooth primary bar only when it's increasing
                bool canGoUp = effectSmoothChangeDirection == SmoothDirection.Both ||
                               effectSmoothChangeDirection == SmoothDirection.OnlyWhenIncreasing;

                if (ValueF > ValueF2 && canGoUp)
                {
                    EnergyBarCommons.SmoothDisplayValue(ref ValueF2, ValueF, effectSmoothChangeSpeed);
                }
                else
                {
                    ValueF2 = energyBar.ValueF;
                }

                if (!Mathf.Approximately(ValueF, ValueF2))
                {
                    effectSmoothChangeWorking = true;
                }
                else if (effectSmoothChangeWorking)
                {
                    effectSmoothChangeFinishedNotify.Execute(this);
                    effectSmoothChangeWorking = false;
                }
            }
            else
            {
                ValueF2 = energyBar.ValueF;
            }
        }
        else
        {
            if (effectSmoothChange)
            {
                bool canGoUp = effectSmoothChangeDirection == SmoothDirection.Both ||
                               effectSmoothChangeDirection == SmoothDirection.OnlyWhenIncreasing;
                bool canGoDown = effectSmoothChangeDirection == SmoothDirection.Both ||
                                 effectSmoothChangeDirection == SmoothDirection.OnlyWhenDecreasing;

                if ((ValueF > ValueF2 && canGoUp) || (ValueF < ValueF2 && canGoDown))
                {
                    EnergyBarCommons.SmoothDisplayValue(ref ValueF2, ValueF, effectSmoothChangeSpeed);
                }
                else
                {
                    ValueF2 = energyBar.ValueF;
                }

                if (!Mathf.Approximately(ValueF, ValueF2))
                {
                    effectSmoothChangeWorking = true;
                }
                else if (effectSmoothChangeWorking)
                {
                    effectSmoothChangeFinishedNotify.Execute(this);
                    effectSmoothChangeWorking = false;
                }
            }
            else
            {
                ValueF2 = energyBar.ValueF;
            }
        }
    }
        void DrawSelectionToolUI()
        {
            GUILayout.Label(selectedCount + " particle(s) selected");

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Invert", GUILayout.Width(88)))
            {
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (actor.active[i])
                    {
                        selectionStatus[i] = !selectionStatus[i];
                    }
                }
                SelectionChanged();
            }
            GUI.enabled = selectedCount > 0;
            if (GUILayout.Button("Clear", GUILayout.Width(88)))
            {
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    selectionStatus[i] = false;
                }
                SelectionChanged();
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Select fixed", GUILayout.Width(88)))
            {
                for (int i = 0; i < actor.invMasses.Length; i++)
                {
                    if (actor.active[i] && actor.invMasses[i] == 0)
                    {
                        selectionStatus[i] = true;
                    }
                }
                SelectionChanged();
            }
            GUI.enabled = selectedCount > 0;
            if (GUILayout.Button("Unselect fixed", GUILayout.Width(88)))
            {
                for (int i = 0; i < actor.invMasses.Length; i++)
                {
                    if (actor.active[i] && actor.invMasses[i] == 0)
                    {
                        selectionStatus[i] = false;
                    }
                }
                SelectionChanged();
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();

            GUI.enabled = selectedCount > 0;
            GUILayout.BeginHorizontal();

            if (GUILayout.Button(new GUIContent("Fix", EditorGUIUtility.Load("PinIcon.psd") as Texture2D), GUILayout.MaxHeight(18), GUILayout.Width(88)))
            {
                Undo.RecordObject(actor, "Fix particles");
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (selectionStatus[i])
                    {
                        if (actor.invMasses[i] != 0)
                        {
                            SetPropertyValue(ParticleProperty.MASS, i, Mathf.Infinity);
                            newProperty         = GetPropertyValue(ParticleProperty.MASS, i);
                            actor.velocities[i] = Vector3.zero;
                        }
                    }
                }
                actor.PushDataToSolver(new ObiSolverData(ObiSolverData.ParticleData.INV_MASSES | ObiSolverData.ParticleData.VELOCITIES));
                EditorUtility.SetDirty(actor);
            }

            if (GUILayout.Button(new GUIContent("Unfix", EditorGUIUtility.Load("UnpinIcon.psd") as Texture2D), GUILayout.MaxHeight(18), GUILayout.Width(88)))
            {
                Undo.RecordObject(actor, "Unfix particles");
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (selectionStatus[i])
                    {
                        if (actor.invMasses[i] == 0)
                        {
                            SetPropertyValue(ParticleProperty.MASS, i, 1);
                        }
                    }
                }
                actor.PushDataToSolver(new ObiSolverData(ObiSolverData.ParticleData.INV_MASSES));
                EditorUtility.SetDirty(actor);
            }

            /*if (GUILayout.Button("CUT")){
             *      ObiCloth mesh = ((ObiCloth)actor);
             *      mesh.DistanceConstraints.RemoveFromSolver(null);
             *      mesh.AerodynamicConstraints.RemoveFromSolver(null);
             *      MeshBuffer buf = new MeshBuffer(mesh.clothMesh);
             *
             *      int[] sel = new int[2];
             *      int k = 0;
             *      for(int i = 0; i < selectionStatus.Length; i++){
             *              if (selectionStatus[i]){
             *                      sel[k] = i;
             *                      k++;
             *                      if (k == 2) break;
             *              }
             *      }
             *
             *      int cindex = -1;
             *      for (int j = 0; j < mesh.DistanceConstraints.restLengths.Count; j++){
             *              if ((mesh.DistanceConstraints.springIndices[j*2] == sel[0] && mesh.DistanceConstraints.springIndices[j*2+1] == sel[1]) ||
             *                  (mesh.DistanceConstraints.springIndices[j*2] == sel[1] && mesh.DistanceConstraints.springIndices[j*2+1] == sel[0])){
             *                      cindex = j;
             *                      break;
             *              }
             *      }
             *      if (cindex >= 0)
             *              mesh.Tear(cindex,buf);
             *
             *
             *      mesh.DistanceConstraints.AddToSolver(mesh);
             *      mesh.AerodynamicConstraints.AddToSolver(mesh);
             *      buf.Apply();
             *
             *      mesh.GetMeshDataArrays(mesh.clothMesh);
             * }*/

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUI.enabled = selectedCount > 0;
            if (GUILayout.Button("Create Handle", GUILayout.Width(180)))
            {
                // Create the handle:
                GameObject c = new GameObject("Obi Handle");
                Undo.RegisterCreatedObjectUndo(c, "Create Obi Particle Handle");
                ObiParticleHandle handle = c.AddComponent <ObiParticleHandle>();
                handle.Actor = actor;

                // Calculate position of handle from average of particle positions:
                Vector3 average = Vector3.zero;
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (selectionStatus[i])
                    {
                        average += wsPositions[i];
                    }
                }

                c.transform.position = average / selectedCount;

                // Add the selected particles to the handle:
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (selectionStatus[i])
                    {
                        handle.AddParticle(i, wsPositions[i], actor.invMasses[i]);
                    }
                }
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            EditorGUI.showMixedValue = false;
            for (int i = 0; i < selectionStatus.Length; i++)
            {
                if (selectionStatus[i] && !Mathf.Approximately(GetPropertyValue(currentProperty, i), selectionProperty))
                {
                    EditorGUI.showMixedValue = true;
                }
            }

            newProperty = EditorGUILayout.FloatField(newProperty, GUILayout.Width(88));
            EditorGUI.showMixedValue = false;

            if (GUILayout.Button("Set " + GetPropertyName(), GUILayout.Width(88)))
            {
                Undo.RecordObject(actor, "Set particle property");
                selectionProperty = newProperty;
                for (int i = 0; i < selectionStatus.Length; i++)
                {
                    if (selectionStatus[i])
                    {
                        SetPropertyValue(currentProperty, i, selectionProperty);
                    }
                }
                ParticlePropertyChanged();
                EditorUtility.SetDirty(actor);
            }

            GUILayout.EndHorizontal();
            GUI.enabled = true;
        }
 public static bool IsUniformScale(Vector3 toCheck)
 {
     return(Mathf.Approximately(toCheck.x, toCheck.y) && Mathf.Approximately(toCheck.y, toCheck.z));
 }
Example #9
0
        private void OrderBySide()
        {
            var increase = Vector3.zero;

            int axisX = _orderAxis & (int)(OrderAxis.X);
            int axisY = _orderAxis & (int)(OrderAxis.X);
            int axisZ = _orderAxis & (int)(OrderAxis.X);

            if (axisX != 0)
            {
                Array.Sort(_gameObjects, (object x, object y) => {
                    GameObject a = (GameObject)x;
                    GameObject b = (GameObject)y;
                    return(a.transform.position.x.CompareTo(b.transform.position.x));
                });

                if (_alignment == TextAlignment.Left)
                {
                    increase.x = _distance;
                }
                else if (_alignment == TextAlignment.Right)
                {
                    Array.Reverse(_gameObjects);
                    increase.x = -_distance;
                }
            }

            if (axisY != 0)
            {
                Array.Sort(_gameObjects, (object x, object y) => {
                    GameObject a = (GameObject)x;
                    GameObject b = (GameObject)y;
                    return(a.transform.position.y.CompareTo(b.transform.position.y));
                });

                if (_alignment == TextAlignment.Left)
                {
                    increase.y = _distance;
                }
                else if (_alignment == TextAlignment.Right)
                {
                    Array.Reverse(_gameObjects);
                    increase.y = -_distance;
                }
            }

            if (axisZ != 0)
            {
                Array.Sort(_gameObjects, (object x, object y) => {
                    GameObject a = (GameObject)x;
                    GameObject b = (GameObject)y;
                    return(a.transform.position.z.CompareTo(b.transform.position.z));
                });

                if (_alignment == TextAlignment.Left)
                {
                    increase.z = _distance;
                }
                else if (_alignment == TextAlignment.Right)
                {
                    Array.Reverse(_gameObjects);
                    increase.z = -_distance;
                }
            }

            var firstPos    = _gameObjects[0].transform.position;
            var increasePos = increase;

            for (var i = 1; i < _gameObjects.Length; i++)
            {
                var pos = _gameObjects[i].transform.position;
                if (!Mathf.Approximately(increase.x, 0))
                {
                    pos.x = firstPos.x + increasePos.x;
                }
                else if (!Mathf.Approximately(increase.y, 0))
                {
                    pos.y = firstPos.y + increasePos.y;
                }
                else if (!Mathf.Approximately(increase.z, 0))
                {
                    pos.z = firstPos.z + increasePos.z;
                }

                _gameObjects[i].transform.position = pos;

                increasePos += increase;
            }
        }
Example #10
0
 public void AddDanger(Vector3 position, float amount)
 {
     for (int index = 0; index < this.All.Count; ++index)
     {
         if (Mathf.Approximately((float)this.All[index].Position.x, (float)position.x) && Mathf.Approximately((float)this.All[index].Position.y, (float)position.y) && Mathf.Approximately((float)this.All[index].Position.z, (float)position.z))
         {
             Memory.SeenInfo seenInfo = this.All[index];
             seenInfo.Danger = amount;
             this.All[index] = seenInfo;
             return;
         }
     }
     this.All.Add(new Memory.SeenInfo()
     {
         Position  = position,
         Timestamp = Time.get_realtimeSinceStartup(),
         Danger    = amount
     });
 }
Example #11
0
 private bool Approximately(Color a, Color b)
 {
     return(Mathf.Approximately(a.r, b.r) &&
            Mathf.Approximately(a.g, b.g) &&
            Mathf.Approximately(a.b, b.b));
 }
Example #12
0
        /// <summary>
        /// Coroutine to handle the transition delay.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerator TransitionLoop()
        {
            // early exit if skipping when in cross transition
            if (SkipOnCrossTransition && TransitionController.Instance.IsInCrossTransition)
            {
                yield break;
            }

            // if delay and duration are both zero then just set to end state, otherwise set to start and transition
            if (Mathf.Approximately(Delay + Duration, 0))
            {
                SetProgressToEnd();
                TransitionStarted();
            }
            else
            {
                TransitionStarted();

                // delay
                if (!Mathf.Approximately(Delay, 0))
                {
                    yield return(new WaitForSeconds(Delay));
                }

                if (SceneChangeMode == SceneChangeModeType.CrossTransition)
                {
                    TransitionController.Instance.IsInCrossTransition = true;
                    yield return
                        (TransitionController.Instance.StartCoroutine(
                             TransitionController.Instance.TakeScreenshotCoroutine()));

                    SetTransitionDisplayedState(true);
                    StartValue = 1;
                    EndValue   = 0;
                    SetProgressToStart();
                    yield return
                        (TransitionController.Instance.StartCoroutine(
                             TransitionController.Instance.LoadSceneAndWaitForLoad(SceneToLoad)));
                }
                else
                {
                    SetTransitionDisplayedState(true);
                    SetProgressToStart();
                }

                // calculate normalised multiplication factor and avoid / by 0 error.
                var normalisedFactor = Mathf.Approximately(Duration, 0) ? float.MaxValue : (1 / Duration);

                // repeat while progress is less than one.
                while (Progress < 1 && !IsStopped)
                {
                    // update progress if not paused
                    if (!IsPaused)
                    {
                        SetProgress(Progress + normalisedFactor * Time.deltaTime);
                    }

                    yield return(0);
                }
            }

            // if we completed and weren't stopped
            if (Mathf.Approximately(Progress, 1) && !IsStopped)
            {
                TransitionCompleted();
            }
        }
        public override void OnInspectorGUI()
        {
            // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
            serializedObject.Update();

            if (Application.isPlaying)
            {
                GUI.enabled = false;
            }

            LightingSystem lightingSystem = (LightingSystem)target;
            Camera         cam            = lightingSystem.GetComponent <Camera>();
            bool           isMobileTarget = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS ||
                                            EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android;

            if (cam == null)
            {
                EditorGUILayout.LabelField("WARNING: No attached camera found.");
            }

            EditorGUILayout.PropertyField(_lightPixelSize, new GUIContent("Light Pixel Size"));

            bool sizeChanged = false;

#if LIGHT2D_2DTK
            var tk2dCamera  = lightingSystem.GetComponent <tk2dCamera>();
            var tk2dCamSize = tk2dCamera == null
                ? (cam == null ? 0 : cam.orthographicSize)
                : tk2dCamera.ScreenExtents.yMax;
            var currSizeChanged = !Mathf.Approximately(tk2dCamSize, _old2dtkCamSize);
            _old2dtkCamSize = tk2dCamSize;
            if (currSizeChanged)
            {
                _sizeChangeTime = DateTime.Now;
            }
            sizeChanged = (DateTime.Now - _sizeChangeTime).TotalSeconds < 0.2f;
#endif
            if (cam != null)
            {
                float size;
                if (cam.orthographic)
                {
#if LIGHT2D_2DTK
                    float zoom = (tk2dCamera == null ? 1 : tk2dCamera.ZoomFactor);
                    size = (cam.orthographicSize * zoom + _lightCameraSizeAdd.floatValue) * 2f;
#else
                    size = (cam.orthographicSize + _lightCameraSizeAdd.floatValue) * 2f;
#endif
                }
                else
                {
                    float halfFov = (cam.fieldOfView + _lightCameraFovAdd.floatValue) * Mathf.Deg2Rad / 2f;
                    size = Mathf.Tan(halfFov) * _lightObstaclesDistance.floatValue * 2;
                }
                if (!Application.isPlaying)
                {
                    int lightTextureHeight = Mathf.RoundToInt(size / _lightPixelSize.floatValue);
                    int oldSize            = lightTextureHeight;
                    lightTextureHeight = EditorGUILayout.IntField("Light Texture Height", lightTextureHeight);
                    if (lightTextureHeight % 2 != 0)
                    {
                        lightTextureHeight++;
                    }
                    if (lightTextureHeight < 16)
                    {
                        if (lightTextureHeight < 8)
                        {
                            lightTextureHeight = 8;
                        }
                        EditorGUILayout.LabelField("WARNING: Light Texture Height is too small.");
                        EditorGUILayout.LabelField(" 50-200 (mobile) and 200-1000 (pc) is recommended.");
                    }
                    if (lightTextureHeight > (isMobileTarget ? 200 : 1000))
                    {
                        if (lightTextureHeight > 2048)
                        {
                            lightTextureHeight = 2048;
                        }
                        EditorGUILayout.LabelField("WARNING: Light Texture Height is too big.");
                        EditorGUILayout.LabelField(" 50-200 (mobile) and 200-1000 (pc) is recommended.");
                    }
                    if (oldSize != lightTextureHeight && !sizeChanged)
                    {
                        _lightPixelSize.floatValue = size / lightTextureHeight;
                    }
                }
            }

            if (cam == null || cam.orthographic)
            {
                EditorGUILayout.PropertyField(_lightCameraSizeAdd, new GUIContent("Light Camera Size Add"));
            }
            else
            {
                EditorGUILayout.PropertyField(_lightCameraFovAdd, new GUIContent("Light Camera Fov Add"));
                EditorGUILayout.PropertyField(_lightObstaclesDistance, new GUIContent("Camera To Light Obstacles Distance"));
            }

            EditorGUILayout.PropertyField(_hdr, new GUIContent("64 Bit Color"));
            EditorGUILayout.PropertyField(_lightObstaclesAntialiasing, new GUIContent("Light Obstacles Antialiasing"));
            EditorGUILayout.PropertyField(_enableNormalMapping, new GUIContent("Normal Mapping"));
            if (_enableNormalMapping.boolValue && isMobileTarget)
            {
                EditorGUILayout.LabelField("WARNING: Normal mapping is not supported on mobiles.");
            }
            EditorGUILayout.PropertyField(_affectOnlyThisCamera, new GUIContent("Affect Only This Camera"));
            _lightTexturesFilterMode.enumValueIndex =
                (int)(FilterMode)EditorGUILayout.EnumPopup("Texture Filtering", (FilterMode)_lightTexturesFilterMode.enumValueIndex);

            EditorGUILayout.PropertyField(_blurLightSources, new GUIContent("Blur Light Sources"));
            if (_blurLightSources.boolValue && _enableNormalMapping.boolValue)
            {
                EditorGUILayout.LabelField("    Blurring light sources with normal mapping enabled\n");
                EditorGUILayout.LabelField("     could significantly reduce lighting quality.");
            }

            bool normalGuiEnableState = GUI.enabled;
            if (!_blurLightSources.boolValue)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.PropertyField(_lightSourcesBlurMaterial, new GUIContent("   Light Sources Blur Material"));
            GUI.enabled = normalGuiEnableState;

            EditorGUILayout.PropertyField(_enableAmbientLight, new GUIContent("Enable Ambient Light"));
            if (!_enableAmbientLight.boolValue)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.PropertyField(_blurAmbientLight, new GUIContent("   Blur Ambient Light"));
            bool oldEnabled = GUI.enabled;
            if (!_blurAmbientLight.boolValue)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.PropertyField(_ambientLightBlurMaterial, new GUIContent("   Ambient Light Blur Material"));
            GUI.enabled = oldEnabled;
            EditorGUILayout.PropertyField(_ambientLightComputeMaterial, new GUIContent("   Ambient Light Compute Material"));
            GUI.enabled = normalGuiEnableState;

            EditorGUILayout.PropertyField(_lightOverlayMaterial, new GUIContent("Light Overlay Material"));
            EditorGUILayout.PropertyField(_lightCamera, new GUIContent("Lighting Camera"));
            EditorGUILayout.PropertyField(_BgCamera, new GUIContent("BG Camera"));
            _lightSourcesLayer.intValue   = EditorGUILayout.LayerField(new GUIContent("Light Sources Layer"), _lightSourcesLayer.intValue);
            _lightObstaclesLayer.intValue = EditorGUILayout.LayerField(new GUIContent("Light Obstacles Layer"), _lightObstaclesLayer.intValue);
            _ambientLightLayer.intValue   = EditorGUILayout.LayerField(new GUIContent("Ambient Light Layer"), _ambientLightLayer.intValue);

            // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
            serializedObject.ApplyModifiedProperties();
        }
        public static Vector2 Slider2D(int id, Vector2 position, CapFunction drawCapFunction, Vector3 planeNormal, Vector3 planePosition)
        {
            EventType eventType = Event.current.GetTypeForControl(id);

            switch (eventType)
            {
            case EventType.MouseDown:
                if (Event.current.button == 0 && HandleUtility.nearestControl == id && !Event.current.alt)
                {
                    GUIUtility.keyboardControl = id;
                    GUIUtility.hotControl      = id;
                    s_CurrentMousePosition     = Event.current.mousePosition;
                    s_DragStartScreenPosition  = Event.current.mousePosition;
                    Vector2 b = HandleUtility.WorldToGUIPoint(position);
                    s_DragScreenOffset = s_CurrentMousePosition - b;
                    EditorGUIUtility.SetWantsMouseJumping(1);

                    Event.current.Use();
                }
                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == id && (Event.current.button == 0 || Event.current.button == 2))
                {
                    GUIUtility.hotControl = 0;
                    Event.current.Use();
                    EditorGUIUtility.SetWantsMouseJumping(0);
                }
                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == id)
                {
                    s_CurrentMousePosition = Event.current.mousePosition;
                    Vector2 center = position;
                    position = GUIToWorld(s_CurrentMousePosition - s_DragScreenOffset, planeNormal, planePosition);
                    if (!Mathf.Approximately((center - position).magnitude, 0f))
                    {
                        GUI.changed = true;
                    }
                    Event.current.Use();
                }
                break;

            case EventType.KeyDown:
                if (GUIUtility.hotControl == id && Event.current.keyCode == KeyCode.Escape)
                {
                    position = GUIToWorld(s_DragStartScreenPosition - s_DragScreenOffset);
                    GUIUtility.hotControl = 0;
                    GUI.changed           = true;
                    Event.current.Use();
                }
                break;
            }

            if (drawCapFunction != null)
            {
                drawCapFunction(id, position, Quaternion.identity, 1f, eventType);
            }

            return(position);
        }
Example #15
0
 public static bool Zero(float v)
 {
     return(Mathf.Approximately(v, 0.0f));
 }
Example #16
0
    private void guidanceProcess()
    {
        if (weaponRef.launched)
        {
            myFlightControl.enabled = true;

            // Target bearing line


            // ============================  ESTIMATIONS

            float deltaVBoost  = Mathf.Min(Mathf.Abs(estimatedTimeToImpact), rocketMotor.burnTime) * rocketMotor.thrustForce;
            float deltaVCruise = Mathf.Min(Mathf.Abs(estimatedTimeToImpact - rocketMotor.burnTime), rocketMotor.cruiseTime) * rocketMotor.cruiseThrust;
            if (estimatedTimeToImpact < rocketMotor.burnTime)
            {
                deltaVCruise = 0;
            }

            //Debug.LogWarning("DeltaVBoost" + deltaVBoost + "DeltaVCruise: " + deltaVCruise);

            // estimate average missile speed based on distance, thrust, remaining burn time, altitude difference
            estimatedMissileVelocityAverage = myRB.velocity +
                                              transform.forward.normalized * deltaVBoost +
                                              transform.forward.normalized * deltaVCruise -
                                              Vector3.up * (targetPos_now.y - transform.position.y) * assumedGravityAccel;
            //estimatedMissileVelocityAverage = myRB.velocity;

            // estimate closing speed -- positive for closing, negative for separating
            Vector3 closingVector = Vector3.Project(estimatedTargetVelocityAverage -
                                                    estimatedMissileVelocityAverage, targetBearingLine);
            float closingSpeed = closingVector.magnitude;

            // if closing vect not in same direction as bearing line, we are separating. Change sign to negative
            if (!Mathf.Approximately(Vector3.Angle(-closingVector, targetBearingLine), 0.0f))
            {
                closingSpeed *= -1;
            }

            // estimate time to intercept
            estimatedTimeToImpact = Vector3.Distance(targetPos_now, transform.position) / closingSpeed;



            float burnTime = rocketMotor.burnTime + rocketMotor.cruiseTime;

            float glideTime = Mathf.Max(0.0f, estimatedTimeToImpact - burnTime);

            estimatedMissileVelocityAverage *= timeRemainDragEstFactor / (glideTime + timeRemainDragEstFactor);

            // estimate target average velocity
            //estimatedTargetVelocityAverage = targetRB.velocity + (targetAccel * estimatedTimeToImpact / 2);
            estimatedTargetVelocityAverage = targetVel_now;

            // Debug.Log("Estimations ------------ estimated missile average velocity: " + estimatedMissileVelocityAverage.magnitude +
            //      " estimated TARGET average velocity: " + estimatedTargetVelocityAverage.magnitude + " estimated time to impact: " +
            //     estimatedTimeToImpact + " seconds, closing speed: " + closingSpeed);

            //  Debug.DrawRay(transform.position, estimatedMissileVelocityAverage, Color.magenta); // show estimated missilve velocity average
            // Debug.DrawRay(targetPos_now, estimatedTargetVelocityAverage, Color.magenta); // estimated target average velocity
            // Debug.DrawRay(transform.position, closingVector, Color.white);

            //==================================  LEAD ANGLE CALCULATION

            // Lead axis (cross of bearing line and target velocity)
            Vector3 leadRotationAxis = Vector3.Cross(targetBearingLine, estimatedTargetVelocityAverage);

            // Target tangential velocity --> missile will try to match its tangential velocity to this
            Vector3 targetTangentialVelocity = Vector3.Project(estimatedTargetVelocityAverage,
                                                               Vector3.Cross(leadRotationAxis, targetBearingLine));



            //Debug.DrawRay(targetPos_now, targetTangentialVelocity, Color.blue);
            //Debug.DrawRay(targetPos_now, estimatedTargetVelocityAverage, Color.cyan);
            //Debug.Log("Estimated target average velocity: " + estimatedTargetVelocityAverage.magnitude);

            // Lead angle -- direction vector
            //  - trig from velocity magnitude to get angle where tangential velocity matches target tangential velocity
            float leadAngleDegrees = Mathf.Rad2Deg * Mathf.Asin(targetTangentialVelocity.magnitude / estimatedMissileVelocityAverage.magnitude);

            leadAngleDegrees = Mathf.Min(leadAngleDegrees, myRadar.scanConeAngle * scanConeFactor);

            //Debug.Log("leadAngleDegrees: " + leadAngleDegrees);

            //Debug.DrawRay(transform.position, leadRotationAxis.normalized * 10f);

            // Lead direction
            Vector3 leadDirection = Quaternion.AngleAxis(leadAngleDegrees, leadRotationAxis) * targetBearingLine.normalized;

            // Show lead direction
            //Debug.DrawRay(transform.position, leadDirection * Vector3.Distance(targetRB.position, transform.position), Color.green);

            // Target bearing line -- uses drawRay to confirm line vector
            //Debug.DrawRay(transform.position, targetBearingLine.normalized *
            //  Vector3.Distance(targetPos_now, transform.position), Color.red);

            //  Corrected velocity -- CYAN
            // Debug.DrawRay(transform.position, leadDirection.normalized * myRB.velocity.magnitude, Color.cyan);

            // // Target's current velocity -- YELLOW
            // Debug.DrawRay(targetPos_now, targetRB.velocity, Color.yellow);

            // Target average velocity
            // Debug.DrawRay(targetPos_now, estimatedTargetVelocityAverage, Color.white);


            // Parallel target bearing line, placed at end of corrected velocity
            //Debug.DrawRay(transform.position + leadDirection.normalized * myRB.velocity.magnitude,
            //  targetBearingLine.normalized * 1000f, Color.magenta);


            //  ==========================  CORRECTIVE TORQUE CALCULATION

            // correctiveTorqueVector -- axis to torque around to move velocity towards lead direction
            //  - cross of velocity and lead direction vector
            //  - magnitude -- angleBetween velocity and lead direction, ratio of angle vs maxAngle (max 1.0)
            //  - projected onto xy plane to nullify any roll requirement
            float currentVelocityErrorAngle = Vector3.Angle(estimatedMissileVelocityAverage, leadDirection); // degrees

            Vector3 correctiveTorqueVect =
                Vector3.ProjectOnPlane(Vector3.Cross(myRB.velocity, leadDirection), transform.forward).normalized * // torque direction
                (Mathf.Min(currentVelocityErrorAngle / maxCorrectionErrorAngle, 1.0f));                             // torque magnitude



            // Debug.DrawRay(transform.position, correctiveTorqueVect * 30f, Color.blue);
            // Debug.DrawRay(transform.position, correctiveTorqueVect.normalized * 30f, Color.green);
            // Debug.DrawRay(transform.position, myRB.velocity, Color.yellow);
            //Debug.DrawRay(transform.position, transform.forward * 100f, Color.white);



            // Convert to yaw/pitch inputs, -1.0 to 1.0
            myFlightControl.input_pitch = transform.InverseTransformDirection(correctiveTorqueVect).x;
            myFlightControl.input_yaw   = transform.InverseTransformDirection(correctiveTorqueVect).y;

            // Debug.Log("Missile pitch input: " + myFlightControl.input_pitch);
        }

        targetPos_prev = targetPos_now;
        targetVel_prev = targetVel_now;
    }
Example #17
0
    void UpdateBurnValue()
    {
        EnergyBarCommons.SmoothDisplayValue(
            ref ValueFBurn, ValueF2, effectSmoothChangeSpeed);
        ValueFBurn = Mathf.Max(ValueFBurn, ValueF2);
        switch (effectBurnDirection)
        {
        case BurnDirection.Both:
            if (ValueF > ValueF2)
            {
                ValueFBurn = ValueF;
            }
            else if (ValueF < ValueF2)
            {
                EnergyBarCommons.SmoothDisplayValue(
                    ref ValueFBurn, ValueF, effectSmoothChangeSpeed);
            }
            else
            {
                ValueFBurn = Mathf.Max(ValueFBurn, ValueF2);
            }

            break;

        case BurnDirection.OnlyWhenDecreasing:
            if (ValueF < ValueF2)
            {
                EnergyBarCommons.SmoothDisplayValue(
                    ref ValueFBurn, ValueF, effectSmoothChangeSpeed);
            }
            else
            {
                ValueFBurn = Mathf.Max(ValueFBurn, ValueF2);
            }

            break;

        case BurnDirection.OnlyWhenIncreasing:
            if (ValueF > ValueF2)
            {
                ValueFBurn = ValueF;
            }
            else
            {
                ValueFBurn = ValueF2;
            }

            break;

        default:
            throw new ArgumentOutOfRangeException();
        }

        if (!Mathf.Approximately(ValueFBurn, ValueF2))
        {
            effectBurnWorking = true;
        }
        else if (effectBurnWorking)
        {
            effectBurnFinishedNotify.Execute(this);
            effectBurnWorking = false;
        }
    }
Example #18
0
        public void     InsertOffset(float yOffset, float deltaOffset, int id = -1)
        {
            if (id != -1)
            {
                for (int i = 0; i < this.list.Count; i++)
                {
                    if (this.list[i].id == id)
                    {
                        this.list[i].postOffset += deltaOffset;
                        if (Mathf.Approximately(this.list[i].offset + this.list[i].postOffset, 0F) == true)
                        {
                            this.list.RemoveAt(i);
                        }

                        lastOffset += deltaOffset;
                        return;
                    }
                }
            }

            float interestOffset = 0F;

            lastOffset += deltaOffset;

            if (this.list.Count > 0)
            {
                if (this.list[0].offset + this.list[0].postOffset > yOffset)
                {
                    if (Mathf.Approximately(this.list[0].postOffset, -deltaOffset) == true)
                    {
                        this.list.RemoveAt(0);
                    }
                    else
                    {
                        this.list.Insert(0, new PointOfInterest()
                        {
                            postOffset = deltaOffset, id = id
                        });
                    }
                    return;
                }
                else
                {
                    for (int j = 0; j < this.list.Count; j++)
                    {
                        interestOffset += this.list[j].offset + this.list[j].postOffset;
                        if (interestOffset > yOffset)
                        {
                            if (this.list[j].id == -1)
                            {
                                if (Mathf.Approximately(this.list[j].postOffset, -deltaOffset) == true)
                                {
                                    this.list.RemoveAt(j);
                                }
                                else if (j + 1 < this.list.Count && Mathf.Approximately(this.list[j + 1].postOffset, -deltaOffset) == true)
                                {
                                    this.list.RemoveAt(j + 1);
                                }
                            }
                            else
                            {
                                this.list.Insert(j, new PointOfInterest()
                                {
                                    postOffset = deltaOffset, id = id
                                });
                            }
                            return;
                        }
                    }
                }
            }

            this.list.Add(new PointOfInterest()
            {
                postOffset = deltaOffset, id = id
            });
        }
Example #19
0
        public override void TickRare()
        {
            if (this.compFlickable.SwitchIsOn)
            {
                float ambientTemperature = base.AmbientTemperature;
                float num;
                if (ambientTemperature > this.compTempControl.targetTemperature - 1f && ambientTemperature < this.compTempControl.targetTemperature + 1f)
                {
                    num = 0f;
                }
                else if (ambientTemperature < this.compTempControl.targetTemperature - 1f)
                {
                    if (ambientTemperature < 20f)
                    {
                        num = 1f;
                    }
                    else if (ambientTemperature > 1000f)
                    {
                        num = 0f;
                    }
                    else
                    {
                        num = Mathf.InverseLerp(1000f, 100f, ambientTemperature);
                    }
                }
                else if (ambientTemperature > this.compTempControl.targetTemperature + 1f)
                {
                    if (ambientTemperature < -50f)
                    {
                        num = -Mathf.InverseLerp(-273f, -50f, ambientTemperature);
                    }
                    else
                    {
                        num = -1f;
                    }
                }
                else
                {
                    num = 0f;
                }
                float energyLimit = this.compTempControl.prop.energyPerSecond * num * 4.16666651f;
                float num2        = GenTemperature.ControlTemperatureTempChange(base.Position, base.Map, energyLimit, this.compTempControl.targetTemperature);
                bool  flag        = !Mathf.Approximately(num2, 0f);

                if (flag)
                {
                    this.energyCostPerSec = compTempControl.prop.energyCostPerSec;
                    if (netPort.TryGetEnergy(energyCostPerSec))
                    {
                        this.GetRoomGroup().Temperature += num2;
                        powerOn = true;
                    }
                    else
                    {
                        powerOn = false;
                    }
                }
                else
                {
                    this.energyCostPerSec = compTempControl.prop.energyCostPerSec * this.compTempControl.prop.lowPowerConsumptionFactor;
                    if (netPort.TryGetEnergy(energyCostPerSec))
                    {
                        powerOn = true;
                    }
                    else
                    {
                        powerOn = false;
                    }
                }
                this.compTempControl.operatingAtHighPower = flag;
            }
        }
        void EatInvalidChars()
        {
            if (isRenamingFilename)
            {
                Event evt = Event.current;
                if (GUIUtility.keyboardControl == m_TextFieldControlID && evt.GetTypeForControl(m_TextFieldControlID) == EventType.KeyDown)
                {
                    string errorMsg = "";

                    string invalidChars = EditorUtility.GetInvalidFilenameChars();
                    if (invalidChars.IndexOf(evt.character) > -1)
                    {
                        errorMsg = "A file name can't contain any of the following characters:\t" + invalidChars;
                    }

                    if (errorMsg != "")
                    {
                        evt.Use();  // Eat character: prevents the textfield from inputting this evt.character
                        ShowMessage(errorMsg);
                    }
                    else
                    {
                        RemoveMessage();
                    }
                }

                // Remove tooltip if screenpos of overlay has changed (handles the case where the main window is being moved or docked window
                // is resized)
                if (evt.type == EventType.Repaint)
                {
                    Rect screenPos = GetScreenRect();
                    if (!Mathf.Approximately(m_LastScreenPosition.x, screenPos.x) || !Mathf.Approximately(m_LastScreenPosition.y, screenPos.y))
                    {
                        RemoveMessage();
                    }
                    m_LastScreenPosition = screenPos;
                }
            }
        }
Example #21
0
        // Handles slider clicks and page scrolls
        void SetSliderValueFromClick()
        {
            if (clampedDragger.dragDirection == ClampedDragger <TValueType> .DragDirection.Free)
            {
                return;
            }

            if (clampedDragger.dragDirection == ClampedDragger <TValueType> .DragDirection.None)
            {
                if (Mathf.Approximately(pageSize, 0.0f))
                {
                    // Jump drag element to current mouse position when user clicks on slider and pageSize == 0
                    float x, y, sliderLength, dragElementLength, dragElementStartPos;

                    if (direction == SliderDirection.Horizontal)
                    {
                        sliderLength      = dragContainer.resolvedStyle.width;
                        dragElementLength = dragElement.resolvedStyle.width;

                        var totalRange = sliderLength - dragElementLength;
                        var targetXPos = clampedDragger.startMousePosition.x - (dragElementLength / 2f);

                        x = Mathf.Max(0f, Mathf.Min(targetXPos, totalRange));
                        y = dragElement.transform.position.y;
                        dragElementStartPos = x;
                    }
                    else
                    {
                        sliderLength      = dragContainer.resolvedStyle.height;
                        dragElementLength = dragElement.resolvedStyle.height;

                        var totalRange = sliderLength - dragElementLength;
                        var targetYPos = clampedDragger.startMousePosition.y - (dragElementLength / 2f);

                        x = dragElement.transform.position.x;
                        y = Mathf.Max(0f, Mathf.Min(targetYPos, totalRange));
                        dragElementStartPos = y;
                    }

                    var pos = new Vector3(x, y, 0);

                    dragElement.transform.position       = pos;
                    dragBorderElement.transform.position = pos;
                    m_DragElementStartPos = new Rect(x, y, dragElement.resolvedStyle.width, dragElement.resolvedStyle.height);

                    // Manipulation becomes a free form drag
                    clampedDragger.dragDirection = ClampedDragger <TValueType> .DragDirection.Free;
                    ComputeValueAndDirectionFromDrag(sliderLength, dragElementLength, dragElementStartPos);
                    return;
                }

                m_DragElementStartPos = new Rect(dragElement.transform.position.x, dragElement.transform.position.y, dragElement.resolvedStyle.width, dragElement.resolvedStyle.height);
            }

            if (direction == SliderDirection.Horizontal)
            {
                ComputeValueAndDirectionFromClick(dragContainer.resolvedStyle.width, dragElement.resolvedStyle.width, dragElement.transform.position.x, clampedDragger.lastMousePosition.x);
            }
            else
            {
                ComputeValueAndDirectionFromClick(dragContainer.resolvedStyle.height, dragElement.resolvedStyle.height, dragElement.transform.position.y, clampedDragger.lastMousePosition.y);
            }
        }
Example #22
0
        void LateUpdate()
        {
            UpdateKeywords();

            // Shader properties
            float motion = CalculateMotion(Time.deltaTime);

            _matTunnel.SetFloat(_propFxInner, motion);
            _matTunnel.SetFloat(_propFxOuter, motion - effectFeather);

            switch (backgroundMode)
            {
            case BackgroundMode.COLOR:
                _matTunnel.SetColor(_propColor, effectColor);
                break;

            case BackgroundMode.CAGE_COLOR:
            case BackgroundMode.BLUR:
            case BackgroundMode.CAGE_SKYBOX:
            case BackgroundMode.SKYBOX:
                Color bkg = applyColorToBackground ? effectColor : Color.white;
                bkg.a = effectColor.a;
                _matTunnel.SetColor(_propColor, bkg);
                break;
            }

            switch (backgroundMode)
            {
            case BackgroundMode.SKYBOX:
                _matTunnel.SetTexture(_propSkybox, effectSkybox);
                break;

            case BackgroundMode.CAGE_SKYBOX:
                _matSkysphere.SetTexture(_propSkybox, effectSkybox);
                break;
            }

            // Update cage objects if necessary
            if (useCage && cageUpdateEveryFrame)
            {
                UpdateCage();
            }

            if (_lastMaskMode != maskMode)
            {
                ResetMaskCommandBuffer();
            }

            if (_lastBlurKernel != blurSamples || !Mathf.Approximately(_lastBlurRadius, blurDistance))
            {
                UpdateBlurKernel();
            }

            bool di = _drawIris;

            if (_wasDrawingIrisEarly != di)
            {
                if (_camHasIrisBuffer && !di)
                {
                    ToggleIrisCommandBuffer(false);
                }
                else if (!_camHasIrisBuffer && di)
                {
                    ToggleIrisCommandBuffer(true);
                }
                _wasDrawingIrisEarly = di;
            }
            if (di)
            {
                float inner = motion * 0.98f;                   // Ensure iris is always a little bigger than image effect aperture
                _matIris.SetFloat(_propFxInner, inner);
                _matIris.SetFloat(_propFxOuter, inner - effectFeather);
            }

            // Fog
            Shader.SetGlobalFloat(_globPropFogDensity, cageFogDensity);
            Shader.SetGlobalFloat(_globPropFogPower, cageFogPower);
            Shader.SetGlobalFloat(_globPropFogBlend, cageFogBlend);
            Shader.SetGlobalColor(_globPropFogColor, effectColor);

            _hasDrawnThisFrame = false;                 // Flag for once-per-frame things in Draw
        }
    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical   = Input.GetAxis("Vertical");

        Vector2 move = new Vector2(horizontal, vertical);

        if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
        {
            lookDirection.Set(move.x, move.y);
            lookDirection.Normalize();
        }

        animator.SetFloat("Look X", lookDirection.x);
        animator.SetFloat("Look Y", lookDirection.y);
        animator.SetFloat("Speed", move.magnitude);

        if (isInvincible)
        {
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer < 0)
            {
                isInvincible = false;
            }
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            Launch();
        }
        if (Input.GetKey("escape"))
        {
            Application.Quit();
        }

        if (Input.GetKeyDown(KeyCode.X))
        {
            RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC"));
            if (hit.collider != null)
            {
                NonPlayerCharacter character = hit.collider.GetComponent <NonPlayerCharacter>();
                if (character != null)
                {
                    character.DisplayDialog();
                }
            }
        }
//work
        if (currentHealth == 0)
        {
            gameOver = true;
            youLose.SetActive(true);
        }
        if (Input.GetKey(KeyCode.R))

        {
            if (gameOver == true)

            {
                Application.LoadLevel(Application.loadedLevel);
            }
            if (gameWin == true)
            {
                Application.LoadLevel(Application.loadedLevel);
            }
        }
//work end
    }
Example #24
0
        private bool IsReachedTargetPoint()
        {
            float distance = Vector2.Distance(thisTransform.position, targetPos);

            return(Mathf.Approximately(distance, 0f));
        }
Example #25
0
        public override bool ApplyPreset(GameObject avatar)
        {
            if (!avatar)
            {
                return(false);
            }

            Undo.RegisterFullObjectHierarchyUndo(avatar, "Apply Pose");

            PumkinsAvatarTools.ResetPose(avatar);

            if (presetMode == PosePresetMode.HumanPose)
            {
                Animator anim = avatar.GetComponent <Animator>();
                if (anim && anim.avatar && anim.avatar.isHuman)
                {
                    Vector3    pos = avatar.transform.position;
                    Quaternion rot = avatar.transform.rotation;

                    avatar.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);

                    var humanPoseHandler = new HumanPoseHandler(anim.avatar, avatar.transform);

                    var humanPose = new HumanPose();
                    humanPoseHandler.GetHumanPose(ref humanPose);

                    humanPose.muscles = muscles;

                    if (PumkinsAvatarTools.Instance.posePresetTryFixSinking)
                    {
                        if (humanPose.bodyPosition.y < 1 && !Mathf.Approximately(humanPose.bodyPosition.y, 0))
                        {
                            PumkinsAvatarTools.Log(Strings.PoseEditor.bodyPositionYTooSmall, LogType.Warning, humanPose.bodyPosition.y.ToString());
                            humanPose.bodyPosition.y = 1;
                        }
                    }

                    if (PumkinsAvatarTools.Instance.posePresetApplyBodyPosition)
                    {
                        humanPose.bodyPosition = bodyPosition;
                    }
                    if (PumkinsAvatarTools.Instance.posePresetApplyBodyRotation)
                    {
                        humanPose.bodyRotation = bodyRotation;
                    }

                    humanPoseHandler.SetHumanPose(ref humanPose);
                    avatar.transform.SetPositionAndRotation(pos, rot);

                    PumkinsPoseEditor.OnPoseWasChanged(PumkinsPoseEditor.PoseChangeType.Reset);
                    return(true);
                }
                else
                {
                    PumkinsAvatarTools.Log(Strings.Log.cantSetPoseNonHumanoid, LogType.Error, name);
                    return(false);
                }
            }
            else
            {
                if (!avatar)
                {
                    return(false);
                }

                for (int i = 0; i < transformPaths.Count; i++)
                {
                    var t = avatar.transform.Find(transformPaths[i]);
                    if (t != null)
                    {
                        t.localEulerAngles = transformRotations[i];
                    }
                }
                return(true);
            }
        }
Example #26
0
    public void checkCache()
    {
        // Point Values
        if (cachedPointValues.Count != pointValues.Count)
        {
            cachedPointValues = new List <Vector2>(pointValues);
            setAllChanged();
        }
        else
        {
            // Vast majority of update loops will need to loop through all the point values and check cache, should be possible to improve performance here
            for (int i = 0; i < pointValues.Count; i++)
            {
                if (!Mathf.Approximately(pointValues[i].x, cachedPointValues[i].x) || !Mathf.Approximately(pointValues[i].y, cachedPointValues[i].y))
                {
                    cachedPointValues = new List <Vector2>(pointValues);
                    setAllChanged();
                    break;
                }
            }
        }
        // x dist between variables
        theGraph.updateCacheAndFlagFloat(ref cachedXDistBetweenPoints, xDistBetweenPoints, ref pointValuesChanged);
        theGraph.updateCacheAndFlagBool(ref cachedUseXDistBetweenToSpace, UseXDistBetweenToSpace, ref pointValuesChanged);
        theGraph.updateCacheAndFlagBool(ref cachedAutoUpdateXDistBetween, AutoUpdateXDistBetween, ref pointValuesChanged);
        // connect first to last
        if (cachedConnectFirstToLast != connectFirstToLast)
        {
            cachedConnectFirstToLast = connectFirstToLast;
            setAllChanged();
        }
        // Others
        theGraph.updateCacheAndFlagBool(ref cachedHidePoints, hidePoints, ref hidePointsChanged);
        theGraph.updateCacheAndFlagBool(ref cachedHideLines, hideLines, ref hideLinesChanged);
        theGraph.updateCacheAndFlagColor(ref cachedLineColor, lineColor, ref lineColorChanged);
        theGraph.updateCacheAndFlagColor(ref cachedPointColor, pointColor, ref pointColorChanged);
        theGraph.updateCacheAndFlagFloat(ref cachedLineScale, lineScale, ref lineScaleChanged);
        theGraph.updateCacheAndFlagFloat(ref cachedPointWidthHeight, pointWidthHeight, ref pointWidthHeightChanged);

        theGraph.updateCacheAndFlagInt(ref cachedPointPrefab, pointPrefab, ref prefabChanged);
        theGraph.updateCacheAndFlagInt(ref cachedLinkPrefab, linkPrefab, ref prefabChanged);
        if (cachedSeriesType != theGraph.graphType)
        {
            cachedSeriesType = theGraph.graphType;
            prefabChanged    = true;
        }
        if (prefabChanged)
        {
            setAllChanged();
        }
        theGraph.updateCacheAndFlagString(ref cachedSeriesName, seriesName, ref seriesNameChanged);
        theGraph.updateCacheAndFlagFloat(ref cachedLegendEntryFontSize, legendEntryFontSize, ref seriesNameChanged);
        theGraph.updateCacheAndFlagFloat(ref cachedLegendEntryLinkSpacing, legendEntryLinkSpacing, ref legendEntryLinkSpacingChanged);
        theGraph.updateCacheAndFlagFloat(ref cachedLinePadding, linePadding, ref linePaddingChanged);
    }
Example #27
0
 public static float Divide(float _numerator, float _denominator)
 {
     return(Mathf.Approximately(_denominator, 0) ? 0 : (_numerator / _denominator));
 }
Example #28
0
    private void DoRealTimeUpdate()
    {
        /* This "Real Time" update is FPS dependent, so the time axis actually represents a number of frames.
         * The waitForSeconds for coroutines does not actually wait for the specified number of seconds, and is also FPS dependent.
         * An FPS independent solution only seems possible with fixedUpdate, which may be added later. */

        float waitTime = 0.0166f;         // Each x-axis unit is 60 frames. This is 1 second at 60 fps.

        realTimeLoopVar += waitTime;

        float yval = getRealTimeRefVal();

        // Add new point or move the last existing point
        if (pointValues.Count > 1)
        {
            // For the third and additional points, calculate slopes and move previous point instead of creating a new point if slopes not significantly different
            float slope1 = (pointValues[pointValues.Count - 1].y - pointValues[pointValues.Count - 2].y)
                           / (pointValues[pointValues.Count - 1].x - pointValues[pointValues.Count - 2].x);
            float slope2 = (yval - pointValues[pointValues.Count - 2].y) / (realTimeLoopVar - pointValues[pointValues.Count - 2].x);

            if (Mathf.Abs(slope1 - slope2) <= Mathf.Abs(slope1) / 1000f)           // Mathf.Approximately not always working, so defining significantly as 10^3 different
            // Slopes about the same, move the last point
            {
                pointValues[pointValues.Count - 1] = new Vector2(realTimeLoopVar, yval);
            }
            else
            {
                // Slopes significantly different, add a new point
                pointValues.Add(new Vector2(realTimeLoopVar, yval));
            }
        }
        else
        {
            // Just add the second point
            pointValues.Add(new Vector2(realTimeLoopVar, yval));
        }

        // If needed, change graph axis boundary and remove or move the first point to keep the series within the graph boundaries
        if (pointValues.Count > 1 && pointValues[pointValues.Count - 1].x > realTimeOrigMax)
        {
            // For the last real time update series update the axis boundaries by the difference
            if (theGraph.orientationType == WMG_Axis_Graph.orientationTypes.vertical)
            {
                theGraph.xAxisMinValue = realTimeLoopVar - realTimeOrigMax;
                theGraph.xAxisMaxValue = realTimeLoopVar;
            }
            else
            {
                theGraph.yAxisMinValue = realTimeLoopVar - realTimeOrigMax;
                theGraph.yAxisMaxValue = realTimeLoopVar;
            }

            // First and second points used to see if the first point should be moved or deleted after incrementing the minimum axis value
            float x1 = pointValues[0].x;
            float x2 = pointValues[1].x;
            float y1 = pointValues[0].y;
            float y2 = pointValues[1].y;

            // Delete or move the very first point to keep the series in the graph boundary when the maximum is increased
            if (Mathf.Approximately(x1 + waitTime, x2))
            {
                pointValues.RemoveAt(0);
            }
            else
            {
                pointValues[0] = new Vector2(x1 + waitTime, y1 + (y2 - y1) / (x2 - x1) * waitTime);
            }
        }
    }
        private void HandleScroll()
        {
            bool    touchDown     = false;
            bool    touching      = false;
            Vector2 currentScroll = Vector2.zero;

            int cidx  = -1;
            int cidxa = -1;

            touchDown |= VRControllers.Instance.GetButtonDown(VRControllerButtons.Touch, out cidx);
            touching  |= VRControllers.Instance.GetButton(VRControllerButtons.Touch, out cidxa);
            if (cidx > -1)
            {
                currentScroll = VRControllers.Instance.GetTouchPos(cidx);
            }
            else if (cidxa > -1)
            {
                currentScroll = VRControllers.Instance.GetTouchPos(cidxa);
            }

            /*
             #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
             * touchDown |= GvrController.TouchDown;
             * touching |= GvrController.IsTouching;
             * currentScroll = GvrController.TouchPos;
             #endif  // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
             */

            if (touchDown && !eligibleForScroll)
            {
                lastScroll        = currentScroll;
                eligibleForScroll = true;
            }
            else if (touching && eligibleForScroll)
            {
                //Debug.Log("currentScroll is " + currentScroll + " , lastScroll is " + lastScroll);
                pointerData.scrollDelta = (currentScroll - lastScroll) * SCROLL_DELTA_MULTIPLIER;

                GameObject currentGameObject = GetCurrentGameObject();
                if (currentGameObject != null && !Mathf.Approximately(pointerData.scrollDelta.sqrMagnitude, 0.0f))
                {
                    GameObject scrollHandler = ExecuteEvents.GetEventHandler <IScrollHandler>(currentGameObject);
                    ExecuteEvents.ExecuteHierarchy(scrollHandler, pointerData, ExecuteEvents.scrollHandler);
                }

                if (scrollEventData == null)
                {
                    scrollEventData = new ScrollEventData(eventSystem);
                }

                if (currentGameObject != null && Mathf.Abs((currentScroll - lastScroll).x) >= 1 && Mathf.Abs(currentScroll.x) > float.Epsilon)
                {
                    scrollEventData.Direction = (currentScroll - lastScroll).x >= 1 ? ScrollEventData.ScrollDirection.Right : ScrollEventData.ScrollDirection.Left;

                    GameObject scrollHandler = ExecuteEvents.GetEventHandler <IScrollToDirectHandler>(currentGameObject);
                    scrollEventData.selectedObject = scrollHandler;
                    ExecuteEvents.Execute(scrollHandler, scrollEventData, VRExecuteEvents.scrollToDirectHandler);
                }

                lastScroll = currentScroll;
            }
            else if (eligibleForScroll)
            {
                eligibleForScroll       = false;
                pointerData.scrollDelta = Vector2.zero;
            }
        }
Example #30
0
    protected override void Update()
    {
        base.Update();
        if (IsPlayer)
        {
            if (InputManager.Instance.AnyDown("JUMP") && IsGrounded)
            {
                if (InputManager.Instance.AnyDown("MOVE_RIGHT"))
                {
                    _velocity = _jumpForce;
                }
                else if (InputManager.Instance.AnyDown("MOVE_LEFT"))
                {
                    _velocity = new Vector2(-_jumpForce.x, _jumpForce.y);
                }
            }

            if (_wormCollectPoint.childCount == 0)
            {
                WormAgent closestWorm = null;
                var       minDist     = float.MaxValue;
                for (var i = 0; i < WormAgent.All.Count; i++)
                {
                    var worm = WormAgent.All[i];
                    var dst  = Vector2.Distance(_wormCollectPoint.position, worm.transform.position);
                    if (dst < minDist && dst < _wormCollectDst)
                    {
                        minDist     = dst;
                        closestWorm = worm;
                    }
                }

                if (closestWorm != null)
                {
                    closestWorm.enabled = false;
                    closestWorm.transform.SetParent(_wormCollectPoint);
                    closestWorm.transform.localPosition = Vector2.zero;
                }
            }
        }
        else if (Time.time >= _nextUpdate)
        {
            _nextUpdate = Time.time + Random.Range(0.5f, 5f);
            _velocity   = new Vector2(Random.value > 0.5f ? _jumpForce.x : -_jumpForce.x, _jumpForce.y);
        }

        if (!Mathf.Approximately(_velocity.x, 0f))
        {
            _facingRight = Mathf.Sign(_velocity.x) > 0f;
        }

        var scale      = transform.localScale;
        var facingSign = _facingRight ? 1 : -1;

        if ((int)Mathf.Sign(scale.x) != facingSign)
        {
            scale.x *= -1f;
        }

        transform.localScale = scale;

        var position = transform.position;

        position          += (Vector3)_velocity * Time.deltaTime;
        position.y         = Mathf.Max(0f, position.y);
        transform.position = position;
        _velocity.y       -= 9.87f * Time.deltaTime;
        if (IsGrounded)
        {
            _velocity = Vector2.zero;
        }
    }