Beispiel #1
0
 private void OnEnable()
 {
     base.GetComponent <Renderer>().sharedMaterial.SetFloat("_MossSpread", Mathf.Clamp01((float)Clock.Day / 10f) * 0.7f + 0.3f);
 }
Beispiel #2
0
        internal MASPageViewport(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth)
            : base(config, prop, comp)
        {
            string variableName = string.Empty;

            if (config.TryGetValue("variable", ref variableName))
            {
                variableName = variableName.Trim();
            }

            screenSize = monitor.screenSize;

            // Set up our surface.
            imageObject                    = new GameObject();
            imageObject.name               = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta));
            imageObject.layer              = pageRoot.gameObject.layer;
            imageObject.transform.parent   = pageRoot;
            imageObject.transform.position = pageRoot.position;
            imageObject.transform.Translate(monitor.screenSize.x * -0.5f, monitor.screenSize.y * -0.5f, depth);

            // add renderer stuff
            MeshFilter meshFilter = imageObject.AddComponent <MeshFilter>();

            meshRenderer  = imageObject.AddComponent <MeshRenderer>();
            mesh          = new Mesh();
            mesh.vertices = new[]
            {
                // LEFT
                new Vector3(-1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(64.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(-1.0f, -1.0f, 0.0f),
                new Vector3(64.0f, -1.0f, 0.0f),

                // RIGHT
                new Vector3(394.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(394.0f, -1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, -1.0f, 0.0f),

                // BOTTOM - note that Y increases from the bottom
                new Vector3(-1.0f, screenSize.y - 32.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y - 32.0f, 0.0f),
                new Vector3(-1.0f, -1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, -1.0f, 0.0f),

                // TOP - note that Y increases from the bottom
                new Vector3(-1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y + 1.0f, 0.0f),
                new Vector3(-1.0f, screenSize.y - 256.0f, 0.0f),
                new Vector3(screenSize.x + 1.0f, screenSize.y - 256.0f, 0.0f),
            };
            mesh.uv = new[]
            {
                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),

                new Vector2(0.0f, 1.0f),
                Vector2.one,
                Vector2.zero,
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new[]
            {
                0, 1, 2,
                1, 3, 2,

                4, 5, 6,
                5, 7, 6,

                8, 9, 10,
                9, 11, 10,

                12, 13, 14,
                13, 15, 14
            };
            mesh.RecalculateBounds();
            mesh.UploadMeshData(false);
            meshFilter.mesh = mesh;

            imageMaterial         = new Material(MASLoader.shaders["MOARdV/Monitor"]);
            imageMaterial.color   = materialColor;
            meshRenderer.material = imageMaterial;
            RenderPage(false);

            string upperLeftCornerName = string.Empty;

            if (!config.TryGetValue("upperLeftCorner", ref upperLeftCornerName))
            {
                throw new ArgumentException("Unable to find 'upperLeftCorner' in VIEWPORT " + name);
            }

            string[] cornerVars = Utility.SplitVariableList(upperLeftCornerName);
            if (cornerVars.Length != 2)
            {
                throw new ArgumentException("Incorrect number of entries in 'upperLeftCorner' in VIEWPORT " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[0], UpdateLeft);
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[1], UpdateTop);

            string lowerRightCornerName = string.Empty;

            if (!config.TryGetValue("lowerRightCorner", ref lowerRightCornerName))
            {
                throw new ArgumentException("Unable to find 'lowerRightCorner' in VIEWPORT " + name);
            }
            cornerVars = Utility.SplitVariableList(lowerRightCornerName);
            if (cornerVars.Length != 2)
            {
                throw new ArgumentException("Incorrect number of entries in 'lowerRightCorner' in VIEWPORT " + name);
            }
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[0], UpdateRight);
            variableRegistrar.RegisterVariableChangeCallback(cornerVars[1], UpdateBottom);

            string colorString = string.Empty;

            if (config.TryGetValue("color", ref colorString))
            {
                string[] startColors = Utility.SplitVariableList(colorString);
                if (startColors.Length < 3 || startColors.Length > 4)
                {
                    throw new ArgumentException("color does not contain 3 or 4 values in VIEWPORT " + name);
                }

                variableRegistrar.RegisterVariableChangeCallback(startColors[0], (double newValue) =>
                {
                    materialColor.r     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                variableRegistrar.RegisterVariableChangeCallback(startColors[1], (double newValue) =>
                {
                    materialColor.g     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                variableRegistrar.RegisterVariableChangeCallback(startColors[2], (double newValue) =>
                {
                    materialColor.b     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                    imageMaterial.color = materialColor;
                });

                if (startColors.Length == 4)
                {
                    variableRegistrar.RegisterVariableChangeCallback(startColors[3], (double newValue) =>
                    {
                        materialColor.a     = Mathf.Clamp01((float)newValue * (1.0f / 255.0f));
                        imageMaterial.color = materialColor;
                    });
                }
            }


            if (!string.IsNullOrEmpty(variableName))
            {
                // Disable the mesh if we're in variable mode
                imageObject.SetActive(false);
                variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback);
            }
            else
            {
                imageObject.SetActive(true);
            }
        }
Beispiel #3
0
        public float UpdateAttack(float dt)
        {
            float speed = attackTime > 0f ? 1f / attackTime : Mathf.Infinity;

            return(attackValue = Mathf.Clamp01(attackValue + dt * speed));
        }
 /// <summary>
 /// The GetStepValue method returns the current position of the slider based on the step value range.
 /// </summary>
 /// <param name="currentValue">The current position value of the slider to get the Step Value for.</param>
 /// <returns>The current Step Value based on the slider position.</returns>
 public virtual float GetStepValue(float currentValue)
 {
     return(Mathf.Round((stepValueRange.minimum + Mathf.Clamp01(currentValue / maximumLength) * (stepValueRange.maximum - stepValueRange.minimum)) / stepSize) * stepSize);
 }
        protected virtual void SetPositionWithNormalizedValue(float givenTargetPosition)
        {
            float positionOnAxis = Mathf.Lerp(controlJoint.linearLimit.limit, -controlJoint.linearLimit.limit, Mathf.Clamp01(givenTargetPosition));

            SnapToPosition(positionOnAxis);
        }
Beispiel #6
0
        /// <summary>
        /// Queries the waves.
        /// </summary>
        public void QueryWaves(WaveQuery query)
        {
            if (m_queryableOverlays.Count == 0)
            {
                return;
            }
            if (!query.sampleOverlay)
            {
                return;
            }

            bool clipOnly = query.mode == QUERY_MODE.CLIP_TEST;

            float x = query.posX;
            float z = query.posZ;

            //Find all the overlays that have a affect on the wave height at this position
            //This will be overlays with a height tex, a height mask or a clip texture
            GetQueryableContaining(x, z, query.overrideIgnoreQuerys, clipOnly);

            float clipSum   = 0.0f;
            float heightSum = 0.0f;
            float maskSum   = 0.0f;

            OverlayClipTexture   clipTex   = null;
            OverlayHeightTexture heightTex = null;

            for (int i = 0; i < m_containingOverlays.Count; i++)
            {
                QueryableOverlayResult result = m_containingOverlays[i];

                //If enable read/write is not enabled on tex it will throw a exception.
                //Catch and ignore.
                try
                {
                    clipTex   = result.overlay.ClipTex;
                    heightTex = result.overlay.HeightTex;

                    //If overlay has a clip tex sample it.
                    if (clipTex.IsDrawable && clipTex.tex is Texture2D)
                    {
                        float clip = (clipTex.tex as Texture2D).GetPixelBilinear(result.u, result.v).a;
                        clipSum += clip * Mathf.Max(0.0f, clipTex.alpha);
                    }

                    //If overlay has a height or mask tex sample it.
                    if (!clipOnly && heightTex.IsDrawable)
                    {
                        float alpha     = heightTex.alpha;
                        float maskAlpha = Mathf.Max(0.0f, heightTex.maskAlpha);

                        float height = 0.0f;
                        float mask   = 0.0f;

                        if (heightTex.tex != null && heightTex.tex is Texture2D)
                        {
                            height = (heightTex.tex as Texture2D).GetPixelBilinear(result.u, result.v).a;
                        }

                        if (heightTex.mask != null && heightTex.mask is Texture2D)
                        {
                            mask = (heightTex.mask as Texture2D).GetPixelBilinear(result.u, result.v).a;
                            mask = Mathf.Clamp01(mask * maskAlpha);
                        }

                        //Apply the height and mask depending on mask mode.
                        if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES)
                        {
                            height *= alpha;
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.OVERLAY)
                        {
                            height *= alpha * mask;
                            mask    = 0;
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES_AND_OVERLAY)
                        {
                            height *= alpha * (1.0f - mask);
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES_AND_OVERLAY_BLEND)
                        {
                            height *= alpha * mask;
                        }

                        if (HeightOverlayBlendMode == OVERLAY_BLEND_MODE.ADD)
                        {
                            heightSum += height;
                            maskSum   += mask;
                        }
                        else if (HeightOverlayBlendMode == OVERLAY_BLEND_MODE.MAX)
                        {
                            heightSum = Mathf.Max(height, heightSum);
                            maskSum   = Mathf.Max(mask, maskSum);
                        }
                    }
                }
                catch {}
            }

            clipSum = Mathf.Clamp01(clipSum);

            if (0.5f - clipSum < 0.0f)
            {
                query.result.isClipped = true;
            }

            maskSum = 1.0f - Mathf.Clamp01(maskSum);

            query.result.height        *= maskSum;
            query.result.displacementX *= maskSum;
            query.result.displacementZ *= maskSum;

            query.result.height += heightSum;

            query.result.overlayHeight = heightSum;
        }
        protected virtual void DrawFlowchartView(Flowchart flowchart)
        {
            Block[] blocks = flowchart.GetComponents <Block>();

            foreach (Block block in blocks)
            {
                flowchart.scrollViewRect.xMin = Mathf.Min(flowchart.scrollViewRect.xMin, block.nodeRect.xMin - 400);
                flowchart.scrollViewRect.xMax = Mathf.Max(flowchart.scrollViewRect.xMax, block.nodeRect.xMax + 400);
                flowchart.scrollViewRect.yMin = Mathf.Min(flowchart.scrollViewRect.yMin, block.nodeRect.yMin - 400);
                flowchart.scrollViewRect.yMax = Mathf.Max(flowchart.scrollViewRect.yMax, block.nodeRect.yMax + 400);
            }

            // Calc rect for script view
            Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.zoom, this.position.height / flowchart.zoom);

            EditorZoomArea.Begin(flowchart.zoom, scriptViewRect);

            DrawGrid(flowchart);

            GLDraw.BeginGroup(scriptViewRect);

            if (Event.current.button == 0 &&
                Event.current.type == EventType.MouseDown &&
                !mouseOverVariables)
            {
                flowchart.selectedBlock = null;
                if (!EditorGUI.actionKey)
                {
                    flowchart.ClearSelectedCommands();
                }
                Selection.activeGameObject = flowchart.gameObject;
            }

            // The center of the Flowchart depends on the block positions and window dimensions, so we calculate it
            // here in the FlowchartWindow class and store it on the Flowchart object for use later.
            CalcFlowchartCenter(flowchart, blocks);

            // Draw connections
            foreach (Block block in blocks)
            {
                DrawConnections(flowchart, block, false);
            }
            foreach (Block block in blocks)
            {
                DrawConnections(flowchart, block, true);
            }

            GUIStyle windowStyle = new GUIStyle();

            windowStyle.stretchHeight = true;

            BeginWindows();

            windowBlockMap.Clear();
            for (int i = 0; i < blocks.Length; ++i)
            {
                Block block = blocks[i];

                float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.blockName)).x + 10;
                float nodeWidthB = 0f;
                if (block.eventHandler != null)
                {
                    nodeWidthB = nodeStyle.CalcSize(new GUIContent(block.eventHandler.GetSummary())).x + 10;
                }

                block.nodeRect.width  = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120);
                block.nodeRect.height = 40;

                if (Event.current.button == 0)
                {
                    if (Event.current.type == EventType.MouseDrag && dragWindowId == i)
                    {
                        block.nodeRect.x += Event.current.delta.x;
                        block.nodeRect.y += Event.current.delta.y;

                        forceRepaintCount = 6;
                    }
                    else if (Event.current.type == EventType.MouseUp &&
                             dragWindowId == i)
                    {
                        Vector2 newPos = new Vector2(block.nodeRect.x, block.nodeRect.y);

                        block.nodeRect.x = startDragPosition.x;
                        block.nodeRect.y = startDragPosition.y;

                        Undo.RecordObject(block, "Node Position");

                        block.nodeRect.x = newPos.x;
                        block.nodeRect.y = newPos.y;

                        dragWindowId      = -1;
                        forceRepaintCount = 6;
                    }
                }

                Rect windowRect = new Rect(block.nodeRect);
                windowRect.x += flowchart.scrollPos.x;
                windowRect.y += flowchart.scrollPos.y;

                GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle);

                GUI.backgroundColor = Color.white;

                windowBlockMap.Add(block);
            }

            EndWindows();

            // Draw Event Handler labels
            foreach (Block block in blocks)
            {
                if (block.eventHandler != null)
                {
                    string handlerLabel            = "";
                    EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block.eventHandler.GetType());
                    if (info != null)
                    {
                        handlerLabel = "<" + info.EventHandlerName + "> ";
                    }

                    GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel);
                    handlerStyle.wordWrap      = true;
                    handlerStyle.margin.top    = 0;
                    handlerStyle.margin.bottom = 0;
                    handlerStyle.alignment     = TextAnchor.MiddleCenter;

                    Rect rect = new Rect(block.nodeRect);
                    rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block.nodeRect.width);
                    rect.x     += flowchart.scrollPos.x;
                    rect.y     += flowchart.scrollPos.y - rect.height;

                    GUI.Label(rect, handlerLabel, handlerStyle);
                }
            }


            // Draw play icons beside all executing blocks
            if (Application.isPlaying)
            {
                foreach (Block b in blocks)
                {
                    if (b.IsExecuting())
                    {
                        b.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
                        b.activeCommand.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
                        forceRepaintCount = 6;
                    }

                    if (b.executingIconTimer > Time.realtimeSinceStartup)
                    {
                        Rect rect = new Rect(b.nodeRect);

                        rect.x     += flowchart.scrollPos.x - 37;
                        rect.y     += flowchart.scrollPos.y + 3;
                        rect.width  = 34;
                        rect.height = 34;

                        if (!b.IsExecuting())
                        {
                            float alpha = (b.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime;
                            alpha     = Mathf.Clamp01(alpha);
                            GUI.color = new Color(1f, 1f, 1f, alpha);
                        }

                        if (GUI.Button(rect, FungusEditorResources.texPlayBig as Texture, new GUIStyle()))
                        {
                            SelectBlock(flowchart, b);
                        }

                        GUI.color = Color.white;
                    }
                }
            }

            PanAndZoom(flowchart);

            GLDraw.EndGroup();

            EditorZoomArea.End();
        }
Beispiel #8
0
    void FixedUpdate()
    {
        particleEmitter.minEmission   = particleEmitter.maxEmission = 25 * Level.ScrollingSpeed;
        particleEmitter.localVelocity = new Vector3(0, -25 * Level.ScrollingSpeed, 0);
        particleEmitter.minEnergy     = particleEmitter.maxEnergy = 2.5f / particleEmitter.localVelocity.y * -25.0f;

        var ss = Level.ScrollingSpeed;

        Color c   = new Color();
        var   cId = RandomHelper.Random.Next(0, 7);

        switch (cId)
        {
        case 0: c = new Color(1, 0, 0, 1.0f); break;

        case 1: c = new Color(0, 1, 0, 1.0f); break;

        case 2: c = new Color(0, 0, 1, 1.0f); break;

        case 3: c = new Color(1, 1, 0, 1.0f); break;

        case 4: c = new Color(1, 0, 1, 1.0f); break;

        case 5: c = new Color(0, 1, 1, 1.0f); break;

        case 6: c = new Color(1, 1, 1, 1.0f); break;
        }

        ca[0] = Color.Lerp(new Color(1, 1, 1, 0.1f), new Color(c.r, c.g, c.b, 0.1f), Mathf.Clamp01(Level.ScrollingSpeed - 1));
        ca[1] = Color.Lerp(new Color(1, 1, 1, 0.2f), new Color(c.r, c.g, c.b, 0.25f), Mathf.Clamp01(Level.ScrollingSpeed - 1));
        ca[2] = Color.Lerp(new Color(1, 1, 1, 0.225f), new Color(c.r, c.g, c.b, 0.3f), Mathf.Clamp01(Level.ScrollingSpeed - 1));
        ca[3] = Color.Lerp(new Color(1, 1, 1, 0.2f), new Color(c.r, c.g, c.b, 0.25f), Mathf.Clamp01(Level.ScrollingSpeed - 1));
        ca[4] = Color.Lerp(new Color(1, 1, 1, 0.1f), new Color(c.r, c.g, c.b, 0.1f), Mathf.Clamp01(Level.ScrollingSpeed - 1));

        pa.colorAnimation = ca;
    }
Beispiel #9
0
 public void ChangeValueF(float valueF)
 {
     ValueF += valueF;
     ValueF  = Mathf.Clamp01(ValueF);
 }
        public override Pose Calculate()
        {
            // Calculate Inputs
            Col.Calculate();
            Sens.Calculate();
            Damp.Calculate();
            FS.Calculate();
            Lock.Calculate();
            DistMax.Calculate();
            DistMin.Calculate();
            PitchMax.Calculate();
            PitchMin.Calculate();
            RollCoef.Calculate();
            FovCoef.Calculate();
            BlurCoef.Calculate();
            OffsetUp.Calculate();
            Offset.Calculate();
            OffsetDown.Calculate();
            Prev.Calculate();


            if (controller != null && controller.executor != null)
            {
                // Fetch vars
                float yaw   = GetFloat("Yaw");
                float pitch = GetFloat("Pitch");
                float roll  = GetFloat("Roll");
                float dist  = GetFloat("Dist");

                float yawWanted   = GetFloat("YawWanted");
                float pitchWanted = GetFloat("PitchWanted");
                float distWanted  = GetFloat("DistWanted");
                float distLevel   = GetFloat("DistLevel");
                //float distVelocity = GetFloat("DistVelocity");

                Vector3   defaultPos    = CameraController.GetGlobalVar("Default Anchor").value_v;
                Transform anchor        = CameraController.GetTransform("Anchor");
                Transform character     = CameraController.GetTransform("Character");
                Vector3   velocity      = controller.executor.GetVar("Driving Velocity").value_v;
                Vector3   rigidbody_vel = controller.executor.GetVar("Rigidbody Velocity").value_v;

                float followSpeed = FS.value.value_f;
                float sens        = Sens.value.value_f;
                bool  lockCursor  = Lock.value.value_b;
                float damp        = Mathf.Clamp(Damp.value.value_f, 0.005f, 1f);
                float dt          = Mathf.Clamp(Time.deltaTime, 0.001f, 0.1f);

                bool  rotButton = InputModule.Axis("Mouse Right Button").value_b&& !GetBool("Mouse Op GUI");
                float mouseX    = InputModule.Axis("Mouse X").value_f;
                float mouseY    = InputModule.Axis("Mouse Y").value_f;
                float JoystickX = SystemSettingData.Instance.UseController ? InControl.InputManager.ActiveDevice.RightStickX * 25f * Time.deltaTime : 0f;
                float JoystickY = SystemSettingData.Instance.UseController ? InControl.InputManager.ActiveDevice.RightStickY * 12f * Time.deltaTime : 0f;
                float mouseW    = GetBool("Mouse On Scroll") ? 0f : InputModule.Axis("Mouse ScrollWheel").value_f;
                bool  inverseX  = GetBool("Inverse X");
                bool  inverseY  = GetBool("Inverse Y");

                //float ACR = GetFloat("Activity Space Size");
                bool clampd = GetBool("Geometry Clampd");

                float distMax  = DistMax.value.value_f;
                float distMin  = DistMin.value.value_f;
                float pitchMax = PitchMax.value.value_f;
                float pitchMin = PitchMin.value.value_f;
                float rollCoef = RollCoef.value.value_f;
                float fovCoef  = FovCoef.value.value_f;
                float blurCoef = BlurCoef.value.value_f;


                // Calc target
                Vector3 target    = Vector3.zero;
                Vector3 target_up = Vector3.up;
                if (character != null)
                {
                    target    = character.position - character.up;
                    target_up = character.up;
                }
                else if (anchor != null)
                {
                    target = anchor.position;
                }
                else
                {
                    target = defaultPos;
                }

                // rotate / zoom
                float dx = 0, dy = 0;
                float dw = -mouseW * 8;
                if (Prev.value.lockCursor || rotButton)
                {
                    dx = Mathf.Clamp(mouseX * sens * (inverseX ? -1f : 1f), -200, 200) * Time.timeScale;
                    dy = Mathf.Clamp(mouseY * sens * (inverseY ? -1f : 1f), -200, 200) * Time.timeScale;
                }

                float mdx = 0, mdy = 0;
                float jdx = 0, jdy = 0;

                mdx = dx;
                mdy = dy;

                jdx = JoystickX * sens * (inverseX ? -1f : 1f) * Time.timeScale;
                jdy = JoystickY * sens * (inverseY ? -1f : 1f) * Time.timeScale;

                dx += jdx;
                dy += jdy;

                dx = Mathf.Clamp(dx, -6 * sens, 6 * sens);
                dy = Mathf.Clamp(dy, -3 * sens, 3 * sens);

                yawWanted   += dx;
                pitchWanted += dy;
                distLevel   += dw;
                distLevel    = Mathf.Clamp(distLevel, distMin, distMax);

                // lock dist
                if (dw != 0)
                {
                    recalcDistTime         = 3f;
                    lockDistAfterClampTime = 0f;
                }
                if (recalcDistTime > 0)
                {
                    recalcDistTime -= Time.deltaTime;
                }
                if (lockDistAfterClampTime > 0)
                {
                    lockDistAfterClampTime -= Time.deltaTime;
                }
                if (clampd)
                {
                    lockDistAfterClampTime = 2f;
                    controller.executor.SetBool("Geometry Clampd", false);
                }

                distWanted = distLevel;

                // record noControlTime
                if (!Prev.value.lockCursor && rotButton)
                {
                    noControlTime = 0;
                }
                else if (Mathf.Abs(jdx) + Mathf.Abs(jdy) > 0.2f || Mathf.Abs(mdx) + Mathf.Abs(mdy) > 8f)
                {
                    noControlTime = 0;
                }
                else
                {
                    noControlTime += dt;
                }

                controller.executor.SetFloat("No Rotate Time", noControlTime);

                // Follow
                if (noControlTime > 2.0f)
                {
                    velUsed = Vector3.Lerp(velUsed, velocity, 0.1f);
                }
                else
                {
                    velUsed = Vector3.Lerp(velUsed, Vector3.zero, 0.5f);
                }
                if (float.IsNaN(velUsed.x) || float.IsNaN(velUsed.y) || float.IsNaN(velUsed.z))
                {
                    velUsed = Vector3.zero;
                }

                float vel_length = Mathf.Clamp01((velUsed.magnitude - 2) * 0.1f);
                float yaw_length = Mathf.Clamp01((new Vector2(velUsed.x, velUsed.z).magnitude - 2) * 0.1f);

                Debug.DrawLine(target, target + velUsed, Color.cyan);
                if (vel_length > 0.01f)
                {
                    Quaternion q      = Quaternion.LookRotation(velUsed);
                    Vector3    euler  = q.eulerAngles;
                    float      fyaw   = euler.y;
                    float      fpitch = -euler.x - 10;

                    fyaw   = Mathf.LerpAngle(yawWanted, fyaw, yaw_length);
                    fpitch = Mathf.LerpAngle(pitchWanted, fpitch, vel_length * 0.02f);

                    yawWanted   = Mathf.SmoothDampAngle(yawWanted, fyaw, ref vyaw, 20.0f / followSpeed);
                    pitchWanted = Mathf.SmoothDampAngle(pitchWanted, fpitch, ref vpitch, 40.0f / followSpeed);

//					float ayaw = Mathf.DeltaAngle(yawWanted, fyaw) * followSpeed * yaw_length;
//					float apitch = Mathf.DeltaAngle(pitchWanted, fpitch) * followSpeed * vel_length;
//
//					ayaw -= (vyaw*vyaw) * Mathf.Sign(vyaw) * 1f;
//					apitch -= (vpitch*vpitch) * Mathf.Sign(vpitch) * 1f;
//
//					ayaw = Mathf.Clamp(ayaw, -2000, 2000);
//					apitch = Mathf.Clamp(apitch, -2000, 2000);
//
//					vyaw = vyaw + ayaw * dt;
//					vpitch = vpitch + apitch * dt;
//
//					vyaw = Mathf.Clamp(vyaw, -60, 60);
//					vpitch = Mathf.Clamp(vpitch, -60, 60);
//
//					yawWanted += vyaw * dt;
//					pitchWanted += vpitch * dt;
                }

                yawWanted   = Mathf.Repeat(yawWanted, 360f);
                pitchWanted = Mathf.Clamp(pitchWanted, pitchMin, pitchMax);
                distWanted  = Mathf.Clamp(distWanted, distMin, distMax);

                yaw   = Mathf.LerpAngle(yaw, yawWanted, damp);
                pitch = Mathf.LerpAngle(pitch, pitchWanted, damp);
                float vdist = controller.executor.GetVar("DistVelocity").value_f;
                if (lockDistAfterClampTime <= 0)
                {
                    dist = Mathf.SmoothDamp(dist, distWanted, ref vdist, 0.5f);
                }
                dist = Mathf.Clamp(dist, distMin, distMax);
                controller.executor.SetVar("DistVelocity", vdist);

                Pose pose = Prev.value;
                pose.eulerAngles = new Vector3(-pitch, yaw, 0);

                Vector3 forward = pose.rotation * Vector3.forward;
                Vector3 right   = pose.rotation * Vector3.right;
                //Vector3 up = pose.rotation * Vector3.up;
                Vector3 lofs = Vector3.zero;
                if (pitch < 0)
                {
                    lofs = Vector3.Slerp(Offset.value.value_v, OffsetDown.value.value_v, pitch / pitchMin);
                }
                else
                {
                    lofs = Vector3.Slerp(Offset.value.value_v, OffsetUp.value.value_v, pitch / pitchMax);
                }
                float _dist = dist;
                if (distMin == distMax)
                {
                    _dist = distMin;
                }
                pose.position   = target - _dist * forward + lofs * _dist;
                pose.lockCursor = lockCursor;

                // Roll
                if (Mathf.Abs(rollCoef) > 0.001f)
                {
                    Vector3 horz_forward = forward;
                    Vector3 horz_right   = right;
                    horz_forward.y = 0;
                    horz_forward.Normalize();
                    horz_right.y = 0;

                    float   udotf   = Vector3.Dot(target_up, horz_forward);
                    Vector3 proj_up = target_up - udotf * horz_forward;
                    float   angle   = Vector3.Angle(proj_up, Vector3.up);
                    float   falloff = 1f - Mathf.Pow((angle - 90f) / 90f, 2);
                    if (angle < 90)
                    {
                        angle = Mathf.Lerp(0, 90, falloff);
                    }
                    else
                    {
                        angle = Mathf.Lerp(180, 90, falloff);
                    }
                    angle *= rollCoef;
                    angle *= -Mathf.Sign(Vector3.Dot(proj_up, horz_right));
                    roll   = Mathf.Lerp(roll, angle, 0.15f);
                }
                else
                {
                    roll = Mathf.Lerp(roll, 0, 0.15f);
                }

                pose.eulerAngles = new Vector3(-pitch, yaw, roll);

                // Fov & blur
                float inc = Mathf.InverseLerp(10, 35, rigidbody_vel.magnitude);
                fovIncr         = Mathf.Lerp(fovIncr, inc * fovCoef, 0.2f);
                pose.fov        = Mathf.Clamp(pose.fov + fovIncr, 10f, 90f);
                blur            = Mathf.Lerp(blur, inc * blurCoef, 0.2f);
                pose.motionBlur = Mathf.Clamp(blur, 0, 0.8f);

                // Set vars
                controller.executor.SetFloat("Yaw", yaw);
                controller.executor.SetFloat("Pitch", pitch);
                controller.executor.SetFloat("Roll", roll);
                controller.executor.SetFloat("Dist", dist);
                controller.executor.SetFloat("YawWanted", yawWanted);
                controller.executor.SetFloat("PitchWanted", pitchWanted);
                controller.executor.SetFloat("DistWanted", distWanted);
                controller.executor.SetFloat("DistLevel", distLevel);

                return(pose);
            }

            return(Pose.Default);
        }
        /// <summary>
        /// Follow spline terrain projection
        /// </summary>
        private void FollowTerrain()
        {
            if (splines == null)
            {
                return;
            }

            //First time or end of segment
            if (_currentIndex == -1 || (_progress >= 1))
            {
                ValidateOrientedPoints();

                _progress     = (_progress >= 1) ? 0f : customStartPosition * 0.01f;
                _currentIndex = (_currentIndex == -1) ? splines[_currentSpline].GetClosestOrientedPointIndex(_progress) : _currentIndex;

                if (_goingForward)
                {
                    _currentIndex++;

                    if (_currentIndex > splines[_currentSpline].OrientedPoints.Length - 2)
                    {
                        if (_currentSpline < splines.Count - 1)
                        {
                            _progress = 0f;
                            _currentSpline++;
                            _currentIndex = 0;
                            CalculateSegmentPositionsAndDirection();

                            if (cycleEndStops == SplineFollowerStops.EachSpline)
                            {
                                _currentStopTime = cycleStopTime;
                            }
                        }
                        else // Reached end of spline list
                        {
                            switch (followerBehaviour)
                            {
                            case SplineFollowerBehaviour.StopAtTheEnd:
                                _progress     = 1f;
                                _currentIndex = splines[_currentSpline].OrientedPoints.Length - 2;
                                CalculateSegmentPositionsAndDirection();
                                break;

                            case SplineFollowerBehaviour.Loop:
                                _currentSpline = 0;
                                _currentIndex  = 0;
                                CalculateSegmentPositionsAndDirection();
                                break;

                            case SplineFollowerBehaviour.BackAndForward:
                                _currentIndex--;
                                speed *= -1;
                                CalculateSegmentPositionsAndDirection(true);
                                break;
                            }

                            if (cycleEndStops == SplineFollowerStops.LastSpline || cycleEndStops == SplineFollowerStops.EachSpline)
                            {
                                _currentStopTime = cycleStopTime;
                            }
                        }
                    }
                    else
                    {
                        CalculateSegmentPositionsAndDirection();
                    }
                }
                else
                {
                    _currentIndex--;

                    if (_currentIndex < 1)
                    {
                        if (_currentSpline > 0)
                        {
                            _progress = 1f;
                            _currentSpline--;
                            _currentIndex = (splines[_currentSpline].OrientedPoints.Length - 1);
                            CalculateSegmentPositionsAndDirection(true);

                            if (cycleEndStops == SplineFollowerStops.EachSpline)
                            {
                                _currentStopTime = cycleStopTime;
                            }
                        }
                        else // Reached end of spline list
                        {
                            switch (followerBehaviour)
                            {
                            case SplineFollowerBehaviour.StopAtTheEnd:
                                _progress     = 1f;
                                _currentIndex = 1;
                                CalculateSegmentPositionsAndDirection(true);
                                break;

                            case SplineFollowerBehaviour.Loop:
                                _currentSpline = splines.Count - 1;
                                _currentIndex  = splines[_currentSpline].OrientedPoints.Length - 1;
                                CalculateSegmentPositionsAndDirection(true);
                                break;

                            case SplineFollowerBehaviour.BackAndForward:
                                _currentIndex++;
                                speed *= -1;
                                CalculateSegmentPositionsAndDirection();
                                break;
                            }

                            if (cycleEndStops == SplineFollowerStops.LastSpline || cycleEndStops == SplineFollowerStops.EachSpline)
                            {
                                _currentStopTime = cycleStopTime;
                            }
                        }
                    }
                    else
                    {
                        CalculateSegmentPositionsAndDirection(true);
                    }
                }

                _currentPosition = _startPosition;
                CalculateTerrainStep();
            }
            else if (SpeedChanged)
            {
                if (DirectionChanged)
                {
                    _progress = (1 - _progress);

                    Vector3 tempPos = _startPosition;
                    _startPosition = _endPosition;
                    _endPosition   = tempPos;

                    Quaternion tempRot = _startRotation;
                    _startRotation = _endRotation;
                    _endRotation   = tempRot;

                    _goingForward = (speed >= 0);
                    _currentIndex = _goingForward ? (_currentIndex - 1) : (_currentIndex + 1);
                }

                CalculateTerrainStep();
            }

            _progress += _step;

            _currentPosition = Vector3.Lerp(_startPosition, _endPosition, Mathf.Clamp01(_progress));
            _currentRotation = Quaternion.Lerp(_startRotation, _endRotation, Mathf.Clamp01(_progress));

            transform.position = _currentPosition;
            if (applySplineRotation)
            {
                transform.rotation = _currentRotation;
            }
        }
Beispiel #12
0
        protected override void OnUpdate(float factor, bool isFinished)
        {
            float t = from + factor * (to - from);

            value = Mathf.Clamp01(t);
        }
        public static void DrawFullScreenEffects()
        {
            if (MPObserver.ObservedPlayer == null)
            {
                return;
            }
            PlayerShip player_ship = MPObserver.ObservedPlayer.c_player_ship;
            Vector2    position;

            position.x = 576f;
            position.y = 576f;
            if (UIManager.ui_bg_fade > 0f)
            {
                UIManager.DrawQuadUIInner(position, 15f, 15f, Color.black, UIManager.ui_bg_fade, 11, 0.8f);
                if (!UIManager.ui_blocker_active && UIManager.ui_bg_fade >= 1f)
                {
                    UIManager.ui_blocker_active = true;
                    GameManager.m_player_ship.c_bright_blocker_go.SetActive(true);
                    if (GameManager.m_mesh_container != null)
                    {
                        GameManager.m_mesh_container.SetActive(false);
                    }
                }
            }
            if (UIManager.ui_blocker_active && UIManager.ui_bg_fade < 1f)
            {
                UIManager.ui_blocker_active = false;
                GameManager.m_player_ship.c_bright_blocker_go.SetActive(false);
                if (GameManager.m_mesh_container != null)
                {
                    GameManager.m_mesh_container.SetActive(true);
                }
            }
            position.x = -576f;
            position.y = 576f;
            if (GameplayManager.GamePaused)
            {
                UIManager.menu_flash_fade = Mathf.Max(0f, UIManager.menu_flash_fade - RUtility.FRAMETIME_UI * 2f);
            }
            else
            {
                UIManager.menu_flash_fade = Mathf.Min(1f, UIManager.menu_flash_fade + RUtility.FRAMETIME_UI * 4f);
            }
            if (UIManager.menu_flash_fade > 0f && (!player_ship.m_dying || player_ship.m_player_died_due_to_timer))
            {
                if (player_ship.m_damage_flash_slow > 0f)
                {
                    float a = UIManager.menu_flash_fade * Mathf.Min(0.1f, player_ship.m_damage_flash_slow * 0.1f) + Mathf.Min(0.2f, player_ship.m_damage_flash_fast * 0.2f);
                    UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_damage, a, 11);
                }
                if (player_ship.m_pickup_flash > 0f)
                {
                    float a2 = UIManager.menu_flash_fade * Mathf.Clamp01(player_ship.m_pickup_flash * player_ship.m_pickup_flash) * 0.25f;
                    UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_white, a2, 11);
                }
                if (player_ship.m_energy_flash > 0f)
                {
                    float a3 = UIManager.menu_flash_fade * (player_ship.m_energy_flash - 0.2f) * (player_ship.m_energy_flash - 0.2f) * 0.15f;
                    UIManager.DrawQuadUI(position, 15f, 15f, UIManager.m_col_hi3, a3, 11);
                }
            }
        }
Beispiel #14
0
        public void QueryWaves(WaveQuery query)
        {
            if (this.m_queryableOverlays.Count == 0)
            {
                return;
            }
            if (!query.sampleOverlay)
            {
                return;
            }
            bool  flag = query.mode == QUERY_MODE.CLIP_TEST;
            float posX = query.posX;
            float posZ = query.posZ;

            this.GetQueryableContaining(posX, posZ, query.overrideIgnoreQuerys, flag);
            float num  = 0f;
            float num2 = 0f;
            float num3 = 0f;

            List <QueryableOverlayResult> .Enumerator enumerator = this.m_containingOverlays.GetEnumerator();
            while (enumerator.MoveNext())
            {
                QueryableOverlayResult current = enumerator.Current;
                try
                {
                    OverlayClipTexture   clipTex   = current.overlay.ClipTex;
                    OverlayHeightTexture heightTex = current.overlay.HeightTex;
                    if (clipTex.IsDrawable && clipTex.tex is Texture2D)
                    {
                        float a = (clipTex.tex as Texture2D).GetPixelBilinear(current.u, current.v).a;
                        num += a * Mathf.Max(0f, clipTex.alpha);
                    }
                    if (!flag && heightTex.IsDrawable)
                    {
                        float alpha = heightTex.alpha;
                        float num4  = Mathf.Max(0f, heightTex.maskAlpha);
                        float num5  = 0f;
                        float num6  = 0f;
                        if (heightTex.tex != null && heightTex.tex is Texture2D)
                        {
                            num5 = (heightTex.tex as Texture2D).GetPixelBilinear(current.u, current.v).a;
                        }
                        if (heightTex.mask != null && heightTex.mask is Texture2D)
                        {
                            num6 = (heightTex.mask as Texture2D).GetPixelBilinear(current.u, current.v).a;
                            num6 = Mathf.Clamp01(num6 * num4);
                        }
                        if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES)
                        {
                            num5 *= alpha;
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.OVERLAY)
                        {
                            num5 *= alpha * num6;
                            num6  = 0f;
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES_AND_OVERLAY)
                        {
                            num5 *= alpha * (1f - num6);
                        }
                        else if (heightTex.maskMode == OVERLAY_MASK_MODE.WAVES_AND_OVERLAY_BLEND)
                        {
                            num5 *= alpha * num6;
                        }
                        if (this.HeightOverlayBlendMode == OVERLAY_BLEND_MODE.ADD)
                        {
                            num2 += num5;
                            num3 += num6;
                        }
                        else if (this.HeightOverlayBlendMode == OVERLAY_BLEND_MODE.MAX)
                        {
                            num2 = Mathf.Max(num5, num2);
                            num3 = Mathf.Max(num6, num3);
                        }
                    }
                }
                catch
                {
                }
            }
            num = Mathf.Clamp01(num);
            if (0.5f - num < 0f)
            {
                query.result.isClipped = true;
            }
            num3 = 1f - Mathf.Clamp01(num3);
            query.result.height        = query.result.height * num3;
            query.result.displacementX = query.result.displacementX * num3;
            query.result.displacementZ = query.result.displacementZ * num3;
            query.result.height        = query.result.height + num2;
            query.result.overlayHeight = num2;
        }
Beispiel #15
0
 private void Update()
 {
     if (this.currentValue != this.targetValue)
     {
         this.currentValue = Mathf.Lerp(this.currentValue, this.targetValue, this.curve.Evaluate(Mathf.Clamp01(this.time / this.duration)));
         this.time        += Time.deltaTime;
     }
 }
Beispiel #16
0
 public void ChangeValueCurrent(int value)
 {
     valueCurrent += value;
     ValueF        = Mathf.Clamp01(ValueF);
 }
Beispiel #17
0
 public void SetProgress(float value)
 {
     this.progress = Mathf.Clamp01(value);
 }
    // Update is called once per frame
    void Update()
    {
        // Inputs
        _verticalInput = Input.GetAxis("Vertical");
        _rotationInput = Input.GetAxis("Horizontal");

        _accelerationInput = _verticalInput > 0.0f ? _verticalInput * _forwardAcceleration :
                             _verticalInput < 0.0f ? _verticalInput * _reverseAcceleration : 0.0f;

        _boostBar.SetSlider(_boostLevel);
        _isBoostActivated = (Input.GetButton("Jump") && _boostLevel > 0.0f) ? true : false;

        // Camera movement
        Vector3 cameraTargetTarget = new Vector3(_rotationInput * _cameraRotationRadius, _cameraTarget.localPosition.y, 0.0f);
        float   cameraSmoothTime   = _cameraSmoothTime;

        if (_isBoostActivated)
        {
            cameraTargetTarget.z = -_boostCameraDelay;
            cameraSmoothTime     = 0.5f;
        }
        _cameraTarget.localPosition = Vector3.SmoothDamp(_cameraTarget.localPosition, cameraTargetTarget, ref _cameraFollowVelocity, _cameraSmoothTime);

        // Update car transform
//        UpdateCarRotation();
        if (_isGrounded || _isBoostActivated)
        {
            float verticalFactor = _verticalInput == 0.0f && (_isBoostActivated || (_isGrounded && _rb.velocity.sqrMagnitude > 1.0f)) ? Mathf.Clamp01(_rb.velocity.sqrMagnitude) : _verticalInput;
            transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles + new Vector3(0.0f, _rotationInput * _rotationStrength * Time.deltaTime * verticalFactor, 0.0f));
        }

        transform.position = _rb.transform.position;
    }
Beispiel #19
0
 public static float bounce(float t)
 {
     return(Mathf.Sin(Mathf.Clamp01(t) * Mathf.PI));
 }
 public float RemainingAmount()
 {
     return(Mathf.Clamp01(currentMP.Value / maxMP.Value));
 }
Beispiel #21
0
    void Update()
    {
        float screechAmount = 0;
        bool  allPopped     = true;
        bool  nonePopped    = true;
        float alwaysScrape  = 0;

        for (int i = 0; i < vp.wheels.Length; i++)
        {
            if (wheels[i].connected)
            {
                if (Mathf.Abs(F.MaxAbs(wheels[i].sidewaysSlip, wheels[i].forwardSlip, alwaysScrape)) - slipThreshold > 0)
                {
                    if (wheels[i].popped)
                    {
                        nonePopped = false;
                    }
                    else
                    {
                        allPopped = false;
                    }
                }

                if (wheels[i].grounded)
                {
                    surfaceType = GroundSurfaceMaster.surfaceTypesStatic[wheels[i].contactPoint.surfaceType];

                    if (surfaceType.alwaysScrape)
                    {
                        alwaysScrape = slipThreshold + Mathf.Min(0.5f, Mathf.Abs(wheels[i].rawRPM * 0.001f));
                    }
                }

                screechAmount = Mathf.Max(screechAmount, Mathf.Pow(Mathf.Clamp01(Mathf.Abs(F.MaxAbs(wheels[i].sidewaysSlip, wheels[i].forwardSlip, alwaysScrape)) - slipThreshold), 2));
            }
        }

        //Set audio clip based on number of wheels popped
        if (surfaceType != null)
        {
            snd.clip = allPopped ? surfaceType.rimSnd : (nonePopped ? surfaceType.tireSnd : surfaceType.tireRimSnd);
        }

        //Set sound volume and pitch
        if (screechAmount > 0)
        {
            if (!snd.isPlaying)
            {
                snd.Play();
                snd.volume = 0;
            }
            else
            {
                snd.volume = Mathf.Lerp(snd.volume, screechAmount * ((vp.groundedWheels * 1.0f) / (wheels.Length * 1.0f)), 2 * Time.deltaTime);
                snd.pitch  = Mathf.Lerp(snd.pitch, 0.5f + screechAmount * 0.9f, 2 * Time.deltaTime);
            }
        }
        else if (snd.isPlaying)
        {
            snd.volume = 0;
            snd.Stop();
        }
    }
    void FixedUpdate()
    {
        if (Live)
        {
            if (Reforming)
            {
                float df = Mathf.Clamp01(reformvalue + (Time.fixedDeltaTime * .25f));
                if (df >= 1f)
                {
                    WobbleTransform.localScale = wobblescale;
                    Reforming   = false;
                    reformvalue = 0f;
                }
                else
                {
                    WobbleTransform.localScale = (wobblescale * Mathf.Pow(reformvalue, 1f / 3f));
                    reformvalue = df;
                }
            }
            else if (Falling)
            {
                if ((Time.time - FallTime) >= 5f)
                {
                    explode();
                }
            }
            else
            {
                if (Autosensing)
                {
                    if (Detected)
                    {
                        if (((Time.time - DetectTime) / DelayTime) < .5f)
                        {
                            WobbleTransform.position = (this.transform.position + wobbledif + new Vector3(Random.value * .1f, 0f, 0f));
                        }
                        else
                        {
                            Detected = false;
                            WobbleTransform.position = (this.transform.position + wobbledif);
                            reform();
                            Falling              = true;
                            FallTime             = Time.time;
                            MyRigidbody.bodyType = RigidbodyType2D.Dynamic;
                        }
                    }
                    else
                    {
                        Astronaut plr = Astronaut.TheAstronaut;

                        if ((plr != null) && (plr.Alive) && (!Astronaut.TheAstronaut.Quelling))
                        {
                            Vector3 dif = (plr.transform.position - this.transform.position);
                            if ((dif.magnitude < 30f) && (Mathf.Abs(dif.x) < 10f) && ((dif.y) < 0f))
                            {
                                RaycastHit2D rh = Physics2D.Linecast(this.transform.position, plr.transform.position, LayerMask.GetMask(new string[] { "Geometry" }));
                                //Debug.Log(rh.distance);

                                if ((rh.distance <= 0f) || true)
                                {
                                    //Line of sight
                                    if (dif.y < 0f)
                                    {
                                        float projectedfalltime = Mathf.Sqrt((this.transform.position.y - plr.transform.position.y) / 9.81f);
                                        if (Mathf.Abs(plr.MyRigidbody.velocity.x) > 0f)
                                        {
                                            float approachtime = ((this.transform.position.x - plr.transform.position.x) / plr.MyRigidbody.velocity.x);
                                            if (approachtime > 0f)
                                            {
                                                float timerequired = (projectedfalltime + DelayTime);
                                                float threshold    = .1f;
                                                if (Mathf.Abs(timerequired - approachtime) <= threshold)
                                                {
                                                    DetectTime = Time.time;
                                                    Detected   = true;
                                                    FragmentTelegraph.Play();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        else
        {
            transform.localScale = (transform.localScale * .5f);
        }
    }
        /// <summary>
        /// The GetPositionFromStepValue returns the position the slider would be at based on the given step value.
        /// </summary>
        /// <param name="givenStepValue">The step value to check the position for.</param>
        /// <returns>The position the slider would be at based on the given step value.</returns>
        public virtual float GetPositionFromStepValue(float givenStepValue)
        {
            float normalizedStepValue = VRTK_SharedMethods.NormalizeValue(givenStepValue, stepValueRange.minimum, stepValueRange.maximum);

            return(Mathf.Lerp(controlJoint.linearLimit.limit, -controlJoint.linearLimit.limit, Mathf.Clamp01(normalizedStepValue)));
        }
Beispiel #24
0
    public override void Update()
    {
        if (popUpTimer > 0)
        {
            popUpTimer -= Time.deltaTime;
        }
        else
        {
            popUpTimer = 0;
        }

        if (shootTimer > 0)
        {
            shootTimer -= Time.deltaTime;
        }
        else
        {
            shootTimer = 0;
        }

        if (curTarget != null)
        {
            lastTarget = curTarget;
        }
        else
        {
            SwitchTarget(lastTarget.tag);
        }

        if (currentCoolDown > 0)
        {
            currentCoolDown -= Time.deltaTime;
        }

        ClampCoolDownTime();

        if (GameObject.FindGameObjectsWithTag(Globals.FORTIFICATION) != null)
        {
            GameObject[] nearestFort = GameObject.FindGameObjectsWithTag(Globals.FORTIFICATION);
            for (int i = 0; i < nearestFort.Length; i++)
            {
                if (Vector3.Distance(nearestFort[i].transform.position, tr.position) <= 10f &&
                    Vector3.Distance(lastTarget.position, tr.position) >= 3f)
                {
                    target = GameController.Instance.FindNearestTarget(Globals.FORTIFICATION, tr).transform;
                }
                else
                {
                    SwitchTarget(lastTarget.tag);
                }
            }
        }

        if (shipTarget)
        {
            if (Vector3.Distance(playerTarget.position, tr.position) > distance)
            {
                SwitchTarget(Globals.SHIP);
                lastTarget = playerTarget;
            }
            else if (Vector3.Distance(playerTarget.position, tr.position) <= distance)
            {
                SwitchTarget(Globals.PLAYER);
                lastTarget = shipTarget;
            }
        }

        if (health.IsDead)
        {
            StopAllCoroutines();
            state             = EnemyState.DEAD;
            rigid.constraints = RigidbodyConstraints.FreezeAll;
            rigid.isKinematic = true;
            flamethrower.Stop();
            audio.clip = groundCrawl;
            audio.loop = true;
            audio.Stop();
        }
        else
        {
            if (popUp)
            {
                tr.position = Vector3.Lerp(tr.position,
                                           new Vector3(tr.position.x, attackHeight, tr.position.z), 0.5f * Time.deltaTime);
                rigid.constraints = RigidbodyConstraints.FreezePosition;

                Vector3 lookPos = target.position;
                lookPos.y = attackHeight;
                Vector3 dir       = (lookPos - tr.position).normalized;
                float   targetRot = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg;
                tr.rotation = Quaternion.Euler(attackRot, targetRot, 0f);
                dust.emit   = false;
            }
            else
            {
                rigid.constraints &= ~RigidbodyConstraints.FreezePositionX;
                rigid.constraints &= ~RigidbodyConstraints.FreezePositionZ;
                flamethrower.Stop();
                dust.emit = true;
                canMove   = true;
                state     = Enemy.EnemyState.CHASING;
            }
        }

        if (!isTakingExtraDamage)
        {
            emitter.emit = false;
        }
        else
        {
            emitter.emit = true;
            if (curDamageMat == fireMat)
            {
                SendMessage("TakeDamage", 1.0f - Mathf.Clamp01(burnDamage / Time.time), SendMessageOptions.DontRequireReceiver);
            }
            else if (curDamageMat == lightningMat)
            {
                SendMessage("TakeDamage", 1.0f - Mathf.Clamp01(lightningDamage / Time.time), SendMessageOptions.DontRequireReceiver);
            }
            else
            {
                // No extra damage taken
            }
        }
    }
Beispiel #25
0
        void OnGUI()
        {
            maxSize = new Vector2(390f, 298f);
            minSize = maxSize;

            GUILayout.Space(10f);

            var centeredStyle = new GUIStyle(GUI.skin.GetStyle("Label"));

            centeredStyle.alignment = TextAnchor.UpperCenter;

            GUILayout.Label(logoTex, centeredStyle);

            GUIStyle contentStyle = new GUIStyle(EditorStyles.label);

            contentStyle.alignment = TextAnchor.MiddleCenter;

            UnityEngine.Audio.AudioMixerGroup prevSfxMixerGroup = config.sfxMixerGroup;
            UnityEngine.Audio.AudioMixerGroup prevBgmMixerGroup = config.bgmMixerGroup;
            LayerMask prevOccludeCheck            = config.occludeCheck;
            float     prevOccludeMultiplier       = config.occludeMultiplier;
            uint      prevMaxAudioSources         = config.maxAudioSources;
            string    prevRuntimeIdentifierPrefix = config.runtimeIdentifierPrefix;


            GUIStyle versionStyle = new GUIStyle(EditorStyles.miniLabel);

            versionStyle.alignment = TextAnchor.MiddleCenter;

            EditorGUILayout.LabelField("Global Config", versionStyle);

            GUILayout.Space(5f);

            EditorGUI.BeginChangeCheck();
            UnityEngine.Audio.AudioMixerGroup sfxMixerGroup = EditorGUILayout.ObjectField(new GUIContent("SFX Mixer Group", "Default SFX Mixer Group Output"), config.sfxMixerGroup, typeof(UnityEngine.Audio.AudioMixerGroup), false) as UnityEngine.Audio.AudioMixerGroup;
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed SFX Mixer Group");
                config.sfxMixerGroup = sfxMixerGroup;
            }

            EditorGUI.BeginChangeCheck();
            UnityEngine.Audio.AudioMixerGroup bgmMixerGroup = EditorGUILayout.ObjectField(new GUIContent("BGM Mixer Group", "Default BGM Mixer Group Output"), config.bgmMixerGroup, typeof(UnityEngine.Audio.AudioMixerGroup), false) as UnityEngine.Audio.AudioMixerGroup;
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed BGM Mixer Group");
                config.bgmMixerGroup = bgmMixerGroup;
            }

            EditorGUI.BeginChangeCheck();
            LayerMask occludeCheck = LayerMaskField(new GUIContent("Occlude Check Layer", "Layer Mask used for check whether or not a collider occludes the sound. Tip: Use a unique layer for the occludable colliders, then you can have more control putting invisible triggers on the objects that you want to occludes sound"), config.occludeCheck);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed Occlude Check Layer");
                config.occludeCheck = occludeCheck;
            }

            EditorGUI.BeginChangeCheck();
            float occludeMultiplier = Mathf.Clamp01(EditorGUILayout.Slider(new GUIContent("Occlude Multiplier", "The higher the value, the less the audio is heard when occluded"), Mathf.Clamp01(config.occludeMultiplier), 0f, 1f));

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed Occlude Multiplier");
                config.occludeMultiplier = occludeMultiplier;
            }

            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();
            string prefix = EditorGUILayout.TextField(new GUIContent("Runtime Identifier Prefix", "The prefix used to define Runtime Identifiers"), config.runtimeIdentifierPrefix);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed Runtime Identifier Prefix");
                config.runtimeIdentifierPrefix = prefix;
            }

            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();
            uint maxAudioSources = (uint)Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Max Audio Sources", "Max pooled Multi Audio Sources"), (int)Mathf.Clamp(config.maxAudioSources, 1, 2048)), 1, 2048);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed Max Audio Sources");
                config.maxAudioSources = maxAudioSources;
            }

            EditorGUILayout.HelpBox("To get the best performance only increase this value if you are having problems when playing pooled audios, otherwise keep this value as low as possible.", MessageType.Info);

            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();
            float dopplerFactor = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("Doppler Factor", "Set how audible the Doppler effect is. Use 0 to disable it. Use 1 make it audible for fast moving objects."), Mathf.Clamp(config.dopplerFactor, 0, 10)), 0, 10);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(config, "Changed Doppler Factor");
                config.dopplerFactor = dopplerFactor;
            }

            if (prevRuntimeIdentifierPrefix != config.runtimeIdentifierPrefix || prevSfxMixerGroup != config.sfxMixerGroup || prevBgmMixerGroup != config.bgmMixerGroup || config.occludeCheck != prevOccludeCheck || prevOccludeMultiplier != config.occludeMultiplier || prevMaxAudioSources != config.maxAudioSources)
            {
                EditorUtility.SetDirty(config);
            }
        }
Beispiel #26
0
    // 本体
    IEnumerator FadeOutCoroutine()
    {
        Debug.Log("fadeOutCroutine");
        while (true)
        {
            // フェードインが終わるまで待機
            if (isFading)
            {
                yield return(0);
            }
            else
            {
                break;
            }
        }

        // 初期化
        float elapsedTime = 0.0f;

        isFading = true;

        // フェード処理
        while (elapsedTime < fadeTime)
        {
            yield return(new WaitForFixedUpdate());

            elapsedTime       += Time.deltaTime;
            fadeMaterial.color = new Color(fadeMaterial.color.r, fadeMaterial.color.g, fadeMaterial.color.b, Mathf.Clamp01(elapsedTime / fadeTime));
        }
        isFading = false;

        yield return(0);
    }
Beispiel #27
0
    public void FixedUpdate()
    {
        //calc grounded
        m_isGrounded = false;
        //reset
        //work out which way the gravity is going
        float playerOffset = 0.5f;

        int[] offsets = { 0, -1, 1 };
        //go between -1 and 1, used as a direction scale
        for (int i = 0; i < 3; i++)
        {
            if (m_gravityDirection == Direction.KLeft || m_gravityDirection == Direction.KRight)
            {
                float   isGravityRight        = Mathf.Sign(Physics.gravity.x);
                Vector3 playerCharacterOffset = new Vector3(0, 0, 0);

                //NOTE: could probably combine playerCharacterOffset and xOffset into one vector
                //offset based on i(direction)
                float yOffset = offsets[i] * playerOffset;
                //draw a debug ray to show off where the ray is
                Debug.DrawRay(transform.position + playerCharacterOffset + new Vector3(-0.5f * isGravityRight, yOffset, 0), Vector3.right * isGravityRight * 2);
                //finally work out if the player is on the ground
                m_isGrounded = Physics.Raycast(transform.position + playerCharacterOffset + new Vector3(-0.5f * isGravityRight, yOffset, 0), Vector3.right * isGravityRight, 2, ~(1 << m_playerLayerMask.value));
                //m_isGrounded = Physics.Raycast(transform.position + offset, Vector3.up * isGravityUp, out hit, 2, ~m_playerLayerMask.value);
                //ok player is grounded, no need to check if other raycasts are hitting the ground/foor
            }
            else
            {
                float   isGravityUp           = Mathf.Sign(Physics.gravity.y);
                Vector3 playerCharacterOffset = new Vector3(0, Mathf.Clamp01(Physics.gravity.y) * 2, 0);

                //NOTE: could probably combine playerCharacterOffset and xOffset into one vector
                //offset based on i(direction)
                float xOffset = offsets[i] * playerOffset;
                //draw a debug ray to show off where the ray is
                Debug.DrawRay(transform.position + playerCharacterOffset + new Vector3(xOffset, -0.5f * isGravityUp, 0), Vector3.up * isGravityUp * 2);
                //finally work out if the player is on the ground
                m_isGrounded = Physics.Raycast(transform.position + playerCharacterOffset + new Vector3(xOffset, -0.5f * isGravityUp, 0), Vector3.up * isGravityUp, 2, ~(1 << m_playerLayerMask.value));
                //m_isGrounded = Physics.Raycast(transform.position + offset, Vector3.up * isGravityUp, out hit, 2, ~m_playerLayerMask.value);
                //ok player is grounded, no need to check if other raycasts are hitting the ground/floor
            }

            if (m_isGrounded)
            {
                break;
            }
        }

        //get key inputs
        m_keyDirections[(int)Direction.KLeft]  = Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow);
        m_keyDirections[(int)Direction.KRight] = Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow);
        m_keyDirections[(int)Direction.KUp]    = Input.GetKey(KeyCode.W) | Input.GetKey(KeyCode.UpArrow);
        m_keyDirections[(int)Direction.KDown]  = Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow);

        Direction moveLeft  = Direction.KLeft;
        Direction moveRight = Direction.KRight;

        switch (m_gravityDirection)
        {
        case Direction.KLeft:
        case Direction.KRight:
            moveLeft  = Direction.KDown;
            moveRight = Direction.KUp;
            break;
            //this part is done by initialization
            //case Direction.KUp:
            //case Direction.KDown:
            //    moveLeft = Direction.KLeft;
            //    moveRight = Direction.KRight;
            //    break;
        }

        //calc movement speed
        if (m_keyDirections[(int)moveLeft])
        {
            if (m_gravityDirection == Direction.KUp || m_gravityDirection == Direction.KLeft)
            {
                m_graphics.transform.localScale = new Vector3(1, 1, 1);
            }
            else
            {
                m_graphics.transform.localScale = new Vector3(-1, 1, 1);
            }
            if (m_moveSpeed > 0)
            {
                m_moveSpeed -= m_acceleration * 4 * Time.deltaTime;
            }
            else if (m_moveSpeed <= 0)
            {
                m_moveSpeed -= m_acceleration * Time.deltaTime;
            }
        }
        else if (m_keyDirections[(int)moveRight])
        {
            if (m_gravityDirection == Direction.KUp || m_gravityDirection == Direction.KLeft)
            {
                m_graphics.transform.localScale = new Vector3(-1, 1, 1);
            }
            else
            {
                m_graphics.transform.localScale = new Vector3(1, 1, 1);
            }
            if (m_moveSpeed < 0)
            {
                m_moveSpeed += m_acceleration * 4 * Time.deltaTime;
            }
            else if (m_moveSpeed >= 0)
            {
                m_moveSpeed += m_acceleration * Time.deltaTime;
            }
        }
        else
        {
            if (m_moveSpeed > m_decelleration * Time.deltaTime)
            {
                m_moveSpeed -= m_decelleration * Time.deltaTime;
            }
            else if (m_moveSpeed < -m_decelleration * Time.deltaTime)
            {
                m_moveSpeed = m_moveSpeed + m_decelleration * Time.deltaTime;
            }
            else
            {
                m_moveSpeed = 0;
            }
        }

        //clamp speed
        m_moveSpeed = Mathf.Clamp(m_moveSpeed, -m_maxSpeed, m_maxSpeed);
        SideMovement();
    }
Beispiel #28
0
 public static float Spring(float start, float end, float value)
 {
     value = Mathf.Clamp01(value);
     value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value)));
     return(start + (end - start) * value);
 }
Beispiel #29
0
        public float UpdateRelease(float dt)
        {
            float speed = releaseTime > 0f ? 1f / releaseTime : Mathf.Infinity;

            return(releaseValue = Mathf.Clamp01(releaseValue + dt * speed));
        }
Beispiel #30
0
        public override void Update()
        {
            if (vc.groundDetection != null)
            {
                for (int i = 0; i < vc.Wheels.Count; i++)
                {
                    Sources[i].volume = 0f;
                    Wheel wheel = vc.Wheels[i];
                    GroundDetection.GroundEntity groundEntity = vc.groundDetection.GetCurrentGroundEntity(wheel.WheelController);

                    if (wheel.IsGrounded && groundEntity != null)
                    {
                        if (groundEntity.surfaceSoundComponent.clip != null)
                        {
                            // Change clips based on surface
                            if (Sources[i].clip != groundEntity.surfaceSoundComponent.clip)
                            {
                                // Change surface clip
                                Sources[i].Stop();
                                Sources[i].clip = groundEntity.surfaceSoundComponent.clip;
                                Sources[i].time = Random.Range(0f, groundEntity.surfaceSoundComponent.clip.length);
                                if (Sources[i].enabled)
                                {
                                    Sources[i].Play();
                                }
                            }

                            // If slipSensitiveSurface (tire only makes noise when under load) make sound dependent on side slip, while on gravel and
                            // similar make sound independent of slip since wheel makes noise at all times (only dependent on speed).
                            float surfaceModifier = 1f;
                            if (groundEntity.slipSensitiveSurfaceSound)
                            {
                                surfaceModifier = (wheel.SmoothSideSlip / vc.sideSlipThreshold) + (wheel.SmoothForwardSlip / vc.forwardSlipThreshold);
                            }

                            // Change surface volume and pitch
                            float newVolume = groundEntity.surfaceSoundComponent.volume * Mathf.Clamp01(vc.Speed / 10f)
                                              * surfaceModifier * volume * groundEntity.surfaceSoundComponent.volume;

                            // Recompile fix
                            if (smoothedVolume == null)
                            {
                                smoothedVolume = new HysteresisSmoothedValue(0, 0.2f, 0.5f);
                            }

                            smoothedVolume.Tick(newVolume);

                            SetVolume(smoothedVolume.Value, i);

                            Source.pitch = pitch * 0.5f + Mathf.Clamp01(vc.Speed / 10f) * 1f;
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < vc.Wheels.Count; i++)
                {
                    Sources[i].volume = 0;
                }
            }
        }