Beispiel #1
0
    public override void Update()
    {
        //       //Debug.DrawLine(OwnerTransform.position + new Vector3(0, 1, 0), OwnerTransform.position + Action.Direction + new Vector3(0, 1, 0));

        //Debug.Log("Update");
        if (State == E_State.E_PREPARING_FOR_USE && PositionOK == false)
        {
            CurrentMoveTime += Time.deltaTime;
            if (CurrentMoveTime >= MoveTime)
            {
                CurrentMoveTime = MoveTime;
                PositionOK      = true;
            }

            float progress = Mathf.Min(1.0f, CurrentMoveTime / MoveTime);

            Owner.BlackBoard.Desires.Rotation = Quaternion.Lerp(StartRotation, FinalRotation, progress);

            Vector3 finalPos = Mathfx.Sinerp(StartPosition, FinalPosition, progress);
            if (Move(finalPos - Transform.position) == false)
            {
                PositionOK = true;
            }
        }

        if (State == E_State.E_PREPARING_FOR_USE && PositionOK)
        {
            State = E_State.E_USING;
            PlayAnim();
        }

        if (State == E_State.E_USING && Action.InterObj.IsInteractionFinished)
        {
            Release();
        }
    }
Beispiel #2
0
        void Update()
        {
            timer += Time.deltaTime * speed;

            myTransform.localScale = Vector3.Lerp(scaleFrom, scaleTo, Mathfx.Hermite(0f, 1f, timer));

            if (timer < 0f && speed < 0f && !IsScaling)
            {
                if (loop)
                {
                    speed = -speed;
                    timer = Mathf.Clamp01(timer);
                }
                else
                {
                    enabled = false;
                }
            }
            else if ((timer > 1f && speed > 0) || (timer < 0f && speed < 0))
            {
                speed = -speed;
                timer = Mathf.Clamp01(timer);
            }
        }
Beispiel #3
0
    public IEnumerator Move(Tiles tile)
    {
        bool cross = false;

        action     = "move";
        origin_pos = transform.localPosition;
        var target_pos = tile.transform.position;

        tile.somethingOn = true;
        tile.unit        = this;

        move_progress = 0f;
        while (true)
        {
            transform.localPosition = new Vector2(Mathfx.Hermite(origin_pos.x, target_pos.x, move_progress), Mathfx.Hermite(origin_pos.y, target_pos.y, move_progress));
            //transform.localPosition = Vector2.Lerp(origin_pos, tile.transform.localPosition, move_progress);
            if (!cross && move_progress > 0.5f)
            {
                groundtile.Flush();
                groundtile = tile;
                cross      = true;
            }
            if (move_progress == 1.0f)
            {
                action = "idle";
                //groundtile.Flush();
                //groundtile = tile;

                yield break;
            }
            move_progress += move_speed * Time.deltaTime;
            move_progress  = move_progress > 1.0f ? 1.0f : move_progress;

            yield return(null);
        }
    }
    private void Update()
    {
        if (_cameraControllers.Count > 0)
        {
            // Align camera with current mount point
            _camera.transform.localPosition = Mathfx.Damp(_camera.transform.localPosition, Vector3.zero, 0.5f, Time.unscaledDeltaTime * 3.0f);
            _camera.transform.localRotation = Mathfx.Damp(_camera.transform.localRotation, Quaternion.identity, 0.5f, Time.unscaledDeltaTime * 3.0f);

            float desiredFov = CurrentCameraController.FieldOfView;
            if (_fovStack.Count > 0)
            {
                desiredFov = _fovStack[_fovStack.Count - 1].Value;
            }

            _camera.fieldOfView = Mathfx.Damp(_camera.fieldOfView, desiredFov, 0.25f, Time.unscaledDeltaTime * 2.0f);
        }

        _shakeTimer -= Time.unscaledDeltaTime;
        if (_shakeTimer > 0)
        {
            float shakeT = Mathf.Clamp01(_shakeTimer / _shakeTime);
            _camera.transform.position += Random.onUnitSphere * Random.value * _shakeMagnitude * shakeT;
        }
    }
    public override void OnUpdate()
    {
        if (_attackStatus == AttackStatus.PREPARING)
        {
            bool dontMove = false;
            if (_rotationOk == false)
            {
                _currentRotationTime += Time.deltaTime;
                if (_currentRotationTime >= _rotationTime)
                {
                    _currentRotationTime = _rotationTime;
                    _rotationOk          = true;
                }
                float      progress = _currentRotationTime / _rotationTime;
                Quaternion rotation = Quaternion.Lerp(_startRotation, _finalRotation, progress);
                Agent.Transform.rotation = rotation;
            }

            if (_positionOK == false)
            {
                _currentMoveTime += Time.deltaTime;
                if (_currentMoveTime >= _moveTime)
                {
                    _currentMoveTime = _moveTime;
                    _positionOK      = true;
                    ParticleTools.Instance.Stop(Agent.particleSystemFlashTust);
                }

                if (_currentMoveTime > 0)
                {
                    float   progress = _currentMoveTime / _moveTime;
                    Vector3 finalPos = Mathfx.Hermite(_startPosition, _finalPosition, progress);
                    //if (MoveToCollideWithEnemy(finalPos, Transform.forward) == false)
                    if (TransformTools.Instance.MoveOnGround(Agent.transform, Agent.CharacterController,
                                                             finalPos - Agent.Transform.position, true) == false)
                    {
                        _positionOK = true;
                        ParticleTools.Instance.Stop(Agent.particleSystemFlashTust);
                    }
                }
            }

            if (_rotationOk && _positionOK)
            {
                _attackStatus = AttackStatus.ATTACKING;
                InitializeAttacking();
            }
        }
        else if (_attackStatus == AttackStatus.ATTACKING)
        {
            _currentMoveTime += Time.deltaTime;
            if (_attackPhaseTime < Time.timeSinceLevelLoad)
            {
                //Debug.Log(Time.timeSinceLevelLoad + " attack phase done");
                _eventAttackMelee.attackPhaseDone = true;
                _attackStatus = AttackStatus.FINISHED;
            }

            if (_currentMoveTime >= _moveTime)
            {
                _currentMoveTime = _moveTime;
            }

            if (_currentMoveTime > 0 && _currentMoveTime <= _moveTime)
            {
                float   progress = Mathf.Min(1.0f, _currentMoveTime / _moveTime);
                Vector3 finalPos = Mathfx.Hermite(_startPosition, _finalPosition, progress);
                //if (MoveToCollideWithEnemy(finalPos, Transform.forward) == false)
                if (TransformTools.Instance.MoveOnGround(Agent.transform, Agent.CharacterController,
                                                         finalPos - Agent.Transform.position, false) == false)
                {
                    _currentMoveTime = _moveTime;
                }
            }

            if (_hitTimeStart == false && _hitTime <= Time.timeSinceLevelLoad)
            {
                _hitTimeStart = true;
                HandleAttackResult.DoMeleeDamage(Agent, _eventAttackMelee.target, Agent.BlackBoard.attackerWeapon,
                                                 _eventAttackMelee.animAttackData, _isCritical, _knockdown,
                                                 _eventAttackMelee.animAttackData.isFatal);

                // 显示刀光(方案1:美术做好mesh,参见player)
                if (_eventAttackMelee.animAttackData.lastAttackInCombo)
                {
                    HandleTrail.ShowTrail(Agent, _eventAttackMelee.animAttackData, 0.4f);
                }
                else
                {
                    HandleTrail.ShowTrail(Agent, _eventAttackMelee.animAttackData, 0.5f);
                }

                /*// 屏幕震动
                 * if (AnimAttackData.LastAttackInCombo || AnimAttackData.ComboStep == 3)
                 *  CameraBehaviour.Instance.ComboShake(AnimAttackData.ComboStep - 3);
                 *
                 * if (Owner.IsPlayer && AnimAttackData.FullCombo)
                 *  GuiManager.Instance.ShowComboMessage(AnimAttackData.ComboIndex);*/
            }
        }
        else if (_attackStatus == AttackStatus.FINISHED && _endOfStateTime <= Time.timeSinceLevelLoad)
        {
            IsFinished = true;
            _eventAttackMelee.IsFinished = true;
        }
    }
        public void BuildRegions()
        {
            AstarProfiler.StartProfile("Build Regions");

            int w = voxelArea.width;
            int d = voxelArea.depth;

            int wd = w * d;

            int expandIterations = 8;

            int spanCount = voxelArea.compactSpanCount;


            //new List<int>(1024);
            //List<int> visited = new List<int>(1024);



#if ASTAR_RECAST_BFS
            ushort[] srcReg = voxelArea.tmpUShortArr;
            if (srcReg.Length < spanCount)
            {
                srcReg = voxelArea.tmpUShortArr = new ushort[spanCount];
            }
            Pathfinding.Util.Memory.MemSet <ushort> (srcReg, 0, sizeof(ushort));
#else
            List <int> stack = Pathfinding.Util.ListPool <int> .Claim(1024);

            ushort[] srcReg  = new ushort[spanCount];
            ushort[] srcDist = new ushort[spanCount];
            ushort[] dstReg  = new ushort[spanCount];
            ushort[] dstDist = new ushort[spanCount];
#endif
            ushort regionId = 2;
            MarkRectWithRegion(0, borderSize, 0, d, (ushort)(regionId | BorderReg), srcReg);        regionId++;
            MarkRectWithRegion(w - borderSize, w, 0, d, (ushort)(regionId | BorderReg), srcReg);        regionId++;
            MarkRectWithRegion(0, w, 0, borderSize, (ushort)(regionId | BorderReg), srcReg);        regionId++;
            MarkRectWithRegion(0, w, d - borderSize, d, (ushort)(regionId | BorderReg), srcReg);        regionId++;



#if ASTAR_RECAST_BFS
            uint level = 0;

            List <Int3> basins = Pathfinding.Util.ListPool <Int3> .Claim(100);          //new List<Int3>();

            // Find "basins"
            DebugReplay.BeginGroup("Basins");
            for (int z = 0, pz = 0; z < wd; z += w, pz++)
            {
                for (int x = 0; x < voxelArea.width; x++)
                {
                    CompactVoxelCell c = voxelArea.compactCells[z + x];

                    for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; i++)
                    {
                        CompactVoxelSpan s        = voxelArea.compactSpans[i];
                        bool             anyBelow = false;

                        if (voxelArea.areaTypes[i] == UnwalkableArea || srcReg[i] != 0)
                        {
                            continue;
                        }

                        for (int dir = 0; dir < 4; dir++)
                        {
                            if (s.GetConnection(dir) != NotConnected)
                            {
                                int nx = x + voxelArea.DirectionX[dir];
                                int nz = z + voxelArea.DirectionZ[dir];

                                int ni2 = (int)(voxelArea.compactCells[nx + nz].index + s.GetConnection(dir));

                                if (voxelArea.dist[i] < voxelArea.dist[ni2])
                                {
                                    anyBelow = true;
                                    break;
                                }


                                //CompactVoxelSpan ns = voxelArea.compactSpans[ni];
                            }
                        }
                        if (!anyBelow)
                        {
                            //Debug.DrawRay (this.ConvertPosition(x,z,i),Vector3.down,Color.red);
                            DebugReplay.DrawCube(this.ConvertPosition(x, z, i), cellScale, Color.red);
                            basins.Add(new Int3(x, i, z));
                            //System.Console.WriteLine ("Basin at " + voxelArea.dist[i]);
                            level = System.Math.Max(level, voxelArea.dist[i]);
                        }
                    }
                }
            }

            //Start at maximum possible distance. & ~1 is rounding down to an even value
            level = (uint)((level + 1) & ~1);

            DebugReplay.EndGroup();
            DebugReplay.BeginGroup("BFS");

            List <Int3> st1 = Pathfinding.Util.ListPool <Int3> .Claim(300);

            List <Int3> st2 = Pathfinding.Util.ListPool <Int3> .Claim(300);

            //bool visited = new bool[voxelArea.compactSpanCount];

            for (;; level -= 2)
            {
                DebugReplay.BeginGroup("BFS " + level);
                //System.Console.WriteLine ("Starting level " + level + " with st1.Count = " + st1.Count);

                int ocount      = st1.Count;
                int expandCount = 0;

                if (ocount == 0)
                {
                    //int c = 0;
                    for (int q = 0; q < basins.Count; q++)
                    {
                        if (voxelArea.dist[basins[q].y] >= level)
                        {
                            DebugReplay.DrawCube(this.ConvertPosition(basins[q].x, basins[q].z, basins[q].y) + Vector3.up, cellScale, new Color(0, 1, 0, 0.5f));
                        }

                        if (srcReg[basins[q].y] == 0 && voxelArea.dist[basins[q].y] >= level)
                        {
                            srcReg[basins[q].y] = 1;
                            st1.Add(basins[q]);
                            //c++;
                            //visited[basins[i].y] = true;
                        }
                    }
                }

                for (int j = 0; j < st1.Count; j++)
                {
                    int x = st1[j].x;
                    int i = st1[j].y;
                    int z = st1[j].z;

                    ushort r = srcReg[i];

                    CompactVoxelSpan s = voxelArea.compactSpans[i];
                    int area           = voxelArea.areaTypes[i];

                    DebugReplay.DrawCube(this.ConvertPosition(x, z, i), cellScale, Mathfx.IntToColor(srcReg[i], 0.7f));

                    bool anyAbove = false;
                    for (int dir = 0; dir < 4; dir++)
                    {
                        if (s.GetConnection(dir) == NotConnected)
                        {
                            continue;
                        }

                        int nx = x + voxelArea.DirectionX[dir];
                        int nz = z + voxelArea.DirectionZ[dir];

                        int ni = (int)voxelArea.compactCells[nx + nz].index + s.GetConnection(dir);

                        if (area != voxelArea.areaTypes[ni])
                        {
                            continue;
                        }

                        if (voxelArea.dist[ni] < level)
                        {
                            anyAbove = true;
                            continue;
                        }


                        if (srcReg[ni] == 0)
                        {
                            bool same = false;
                            for (int v = (int)voxelArea.compactCells[nx + nz].index, vt = (int)voxelArea.compactCells[nx + nz].index + (int)voxelArea.compactCells[nx + nz].count; v < vt; v++)
                            {
                                if (srcReg[v] == srcReg[i])
                                {
                                    same = true;
                                    break;
                                }
                            }

                            if (!same)
                            {
                                //if ((int)srcDist[ni]+2 < (int)d2)
                                //{
                                //visited[i] = true;
                                srcReg[ni] = r;
                                //Debug.DrawRay (ConvertPosition(x,z,i),Vector3.up,Mathfx.IntToColor((int)level,0.6f));

                                //if (dstReg[ni] == 0)
                                st1.Add(new Int3(nx, ni, nz));
                                //d2 = (ushort)(srcDist[ni]+2);
                                //}
                            }
                        }
                    }

                    //Still on the edge
                    if (anyAbove)
                    {
                        st2.Add(st1[j]);
                    }

                    if (j == ocount - 1)
                    {
                        expandCount++;
                        ocount = st1.Count;

                        if (expandCount == 8 || j == st1.Count - 1)
                        {
                            //int c = 0;
                            for (int q = 0; q < basins.Count; q++)
                            {
                                if (voxelArea.dist[basins[q].y] >= level)
                                {
                                    DebugReplay.DrawCube(this.ConvertPosition(basins[q].x, basins[q].z, basins[q].y) + Vector3.up, cellScale, new Color(0, 1, 0, 0.5f));
                                }

                                if (srcReg[basins[q].y] == 0 && voxelArea.dist[basins[q].y] >= level)
                                {
                                    srcReg[basins[q].y] = 1;
                                    st1.Add(basins[q]);
                                    //c++;
                                    //visited[basins[i].y] = true;
                                }
                            }
                        }
                    }
                }



                List <Int3> tmpList = st1;
                st1 = st2;
                st2 = tmpList;
                st2.Clear();

                //System.Console.WriteLine ("Flooding basins");

                for (int i = 0; i < basins.Count; i++)
                {
                    if (srcReg[basins[i].y] == 1)
                    {
                        st2.Add(basins[i]);
                        FloodOnes(st2, srcReg, level, regionId); regionId++;
                        st2.Clear();
                    }
                }


                //System.Console.WriteLine ("Added " + c + " basins");
                DebugReplay.EndGroup();
                if (level == 0)
                {
                    break;
                }
            }

            DebugReplay.EndGroup();

            Pathfinding.Util.ListPool <Int3> .Release(st1);

            Pathfinding.Util.ListPool <Int3> .Release(st2);

            Pathfinding.Util.ListPool <Int3> .Release(basins);

            // Filter out small regions.
            voxelArea.maxRegions = regionId;

            FilterSmallRegions(srcReg, minRegionSize, voxelArea.maxRegions);


            // Write the result out.
            for (int i = 0; i < voxelArea.compactSpanCount; i++)
            {
                voxelArea.compactSpans[i].reg = srcReg[i];
            }
#else       /// ====== Use original recast code ====== //
            //Start at maximum possible distance. & ~1 is rounding down to an even value
            uint level = (uint)((voxelArea.maxDistance + 1) & ~1);

            int count = 0;



            while (level > 0)
            {
                level = level >= 2 ? level - 2 : 0;

                AstarProfiler.StartProfile("--Expand Regions");
                if (ExpandRegions(expandIterations, level, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
                {
                    ushort[] tmp = srcReg;
                    srcReg = dstReg;
                    dstReg = tmp;

                    tmp     = srcDist;
                    srcDist = dstDist;
                    dstDist = tmp;
                }

                AstarProfiler.EndProfile("--Expand Regions");

                AstarProfiler.StartProfile("--Mark Regions");


                // Mark new regions with IDs.
                // Find "basins"
                for (int z = 0, pz = 0; z < wd; z += w, pz++)
                {
                    for (int x = 0; x < voxelArea.width; x++)
                    {
                        CompactVoxelCell c = voxelArea.compactCells[z + x];

                        for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; i++)
                        {
                            if (voxelArea.dist[i] < level || srcReg[i] != 0 || voxelArea.areaTypes[i] == UnwalkableArea)
                            {
                                continue;
                            }

                            if (FloodRegion(x, z, i, level, regionId, srcReg, srcDist, stack))
                            {
                                regionId++;
                            }
                        }
                    }
                }


                AstarProfiler.EndProfile("--Mark Regions");

                count++;

                //if (count == 10) {
                //	return;
                //}
            }

            if (ExpandRegions(expandIterations * 8, 0, srcReg, srcDist, dstReg, dstDist, stack) != srcReg)
            {
                ushort[] tmp = srcReg;
                srcReg = dstReg;
                dstReg = tmp;

                tmp     = srcDist;
                srcDist = dstDist;
                dstDist = tmp;
            }

            // Filter out small regions.
            voxelArea.maxRegions = regionId;

            FilterSmallRegions(srcReg, minRegionSize, voxelArea.maxRegions);

            // Write the result out.
            for (int i = 0; i < voxelArea.compactSpanCount; i++)
            {
                voxelArea.compactSpans[i].reg = srcReg[i];
            }

            Pathfinding.Util.ListPool <int> .Release(stack);


            /*
             * int sCount = voxelArea.GetSpanCount ();
             * Vector3[] debugPointsTop = new Vector3[sCount];
             * Vector3[] debugPointsBottom = new Vector3[sCount];
             * Color[] debugColors = new Color[sCount];
             *
             * int debugPointsCount = 0;
             * //int wd = voxelArea.width*voxelArea.depth;
             *
             * for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
             *      for (int x=0;x < voxelArea.width;x++) {
             *
             *              Vector3 p = new Vector3(x,0,pz)*cellSize+forcedBounds.min;
             *
             *              //CompactVoxelCell c = voxelArea.compactCells[x+z];
             *              CompactVoxelCell c = voxelArea.compactCells[x+z];
             *              //if (c.count == 0) {
             *              //	Debug.DrawRay (p,Vector3.up,Color.red);
             *              //}
             *
             *              //for (int i=(int)c.index, ni = (int)(c.index+c.count);i<ni;i++)
             *
             *              for (int i = (int)c.index; i < c.index+c.count; i++) {
             *                      CompactVoxelSpan s = voxelArea.compactSpans[i];
             *                      //CompactVoxelSpan s = voxelArea.compactSpans[i];
             *
             *                      p.y = ((float)(s.y+0.1F))*cellHeight+forcedBounds.min.y;
             *
             *                      debugPointsTop[debugPointsCount] = p;
             *
             *                      p.y = ((float)s.y)*cellHeight+forcedBounds.min.y;
             *                      debugPointsBottom[debugPointsCount] = p;
             *
             *                      debugColors[debugPointsCount] = Pathfinding.Mathfx.IntToColor(s.reg,0.7f);//s.reg == 1 ? Color.green : (s.reg == 2 ? Color.yellow : Color.red);
             *                      debugPointsCount++;
             *
             *                      //Debug.DrawRay (p,Vector3.up*0.5F,Color.green);
             *              }
             *      }
             * }
             *
             * DebugUtility.DrawCubes (debugPointsTop,debugPointsBottom,debugColors, cellSize);*/
#endif
            AstarProfiler.EndProfile("Build Regions");
        }
Beispiel #7
0
 public void tick(float dt)
 {
     this.currentPosition   += dt * this.direction * 1f / this.duration;
     this.currentPosition    = Mathf.Clamp01(this.currentPosition);
     this.axis.localRotation = Quaternion.Lerp(this.fromRotation, this.toRotation, Mathfx.Hermite(0f, 1f, this.currentPosition));
 }
        public override void Drive(FlightCtrlState s)
        {
            float threshold = 0.1F;
            bool  _userCommandingRotation = !(Mathfx.Approx(s.pitch, s.pitchTrim, threshold) &&
                                              Mathfx.Approx(s.yaw, s.yawTrim, threshold) &&
                                              Mathfx.Approx(s.roll, s.rollTrim, threshold));
            bool _userCommandingTranslation = !(Math.Abs(s.X) < threshold &&
                                                Math.Abs(s.Y) < threshold &&
                                                Math.Abs(s.Z) < threshold);

            if (_userCommandingRotation && !_userCommandingTranslation)
            {
                userCommandingRotationSmoothed = 2;
            }
            else if (userCommandingRotationSmoothed > 0)
            {
                userCommandingRotationSmoothed--;
            }

            if (core.GetComputerModule <MechJebModuleThrustWindow>().hidden&& core.GetComputerModule <MechJebModuleAscentGuidance>().hidden)
            {
                return;
            }

            if ((tmode != TMode.OFF) && (vesselState.thrustAvailable > 0))
            {
                double spd = 0;

                switch (tmode)
                {
                case TMode.KEEP_ORBITAL:
                    spd = vesselState.speedOrbital;
                    break;

                case TMode.KEEP_SURFACE:
                    spd = vesselState.speedSurface;
                    break;

                case TMode.KEEP_VERTICAL:
                    spd = vesselState.speedVertical;
                    Vector3d rot = Vector3d.up;
                    if (trans_kill_h)
                    {
                        Vector3 hsdir = Vector3.ProjectOnPlane(vesselState.surfaceVelocity, vesselState.up);
                        Vector3 dir   = -hsdir + vesselState.up * Math.Max(Math.Abs(spd), 20 * mainBody.GeeASL);
                        if ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) > 5000) && (hsdir.magnitude > Math.Max(Math.Abs(spd), 100 * mainBody.GeeASL) * 2))
                        {
                            tmode         = TMode.DIRECT;
                            trans_spd_act = 100;
                            rot           = -hsdir;
                        }
                        else
                        {
                            rot = dir.normalized;
                        }
                        core.attitude.attitudeTo(rot, AttitudeReference.INERTIAL, null);
                    }
                    break;
                }

                double t_err = (trans_spd_act - spd) / vesselState.maxThrustAccel;
                if ((tmode == TMode.KEEP_ORBITAL && Vector3d.Dot(vesselState.forward, vesselState.orbitalVelocity) < 0) ||
                    (tmode == TMode.KEEP_SURFACE && Vector3d.Dot(vesselState.forward, vesselState.surfaceVelocity) < 0))
                {
                    //allow thrust to declerate
                    t_err *= -1;
                }

                double t_act = pid.Compute(t_err);

                if ((tmode != TMode.KEEP_VERTICAL) ||
                    !trans_kill_h ||
                    (core.attitude.attitudeError < 2) ||
                    ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) < 1000) && (core.attitude.attitudeError < 90)))
                {
                    if (tmode == TMode.DIRECT)
                    {
                        trans_prev_thrust = targetThrottle = trans_spd_act / 100.0F;
                    }
                    else
                    {
                        trans_prev_thrust = targetThrottle = Mathf.Clamp01(trans_prev_thrust + (float)t_act);
                    }
                }
                else
                {
                    bool useGimbal = (vesselState.torqueFromEngine.x / vessel.ctrlState.mainThrottle > vesselState.torqueAvailable.x * 10) ||
                                     (vesselState.torqueFromEngine.z / vessel.ctrlState.mainThrottle > vesselState.torqueAvailable.z * 10);

                    bool useDiffThrottle = (vesselState.torqueFromDiffThrottle.x > vesselState.torqueAvailable.x * 10) ||
                                           (vesselState.torqueFromDiffThrottle.z > vesselState.torqueAvailable.z * 10);

                    if ((core.attitude.attitudeError >= 2) && (useGimbal || (useDiffThrottle && core.thrust.differentialThrottle)))
                    {
                        trans_prev_thrust = targetThrottle = 0.1F;
                    }
                    else
                    {
                        trans_prev_thrust = targetThrottle = 0;
                    }
                }
            }

            // Only set throttle if a module need it. Othewise let the user or other mods set it
            // There is always at least 1 user : the module itself (why ?)
            if (users.Count() > 1)
            {
                s.mainThrottle = targetThrottle;
            }

            float throttleLimit = 1;

            limiter = LimitMode.None;

            if (limitThrottle)
            {
                if (maxThrottle < throttleLimit)
                {
                    limiter = LimitMode.Throttle;
                }
                throttleLimit = Mathf.Min(throttleLimit, (float)maxThrottle);
            }

            if (limitToTerminalVelocity)
            {
                float limit = TerminalVelocityThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.TerminalVelocity;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (limitDynamicPressure)
            {
                float limit = MaximumDynamicPressureThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.DynamicPressure;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (limitToPreventOverheats)
            {
                float limit = (float)TemperatureSafetyThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.Temperature;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (limitAcceleration)
            {
                float limit = AccelerationLimitedThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.Acceleration;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (electricThrottle && ElectricEngineRunning())
            {
                float limit = ElectricThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.Electric;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (limitToPreventFlameout)
            {
                // This clause benefits being last: if we don't need much air
                // due to prior limits, we can close some intakes.
                float limit = FlameoutSafetyThrottle();
                if (limit < throttleLimit)
                {
                    limiter = LimitMode.Flameout;
                }
                throttleLimit = Mathf.Min(throttleLimit, limit);
            }

            if (limiterMinThrottle && limiter != LimitMode.None && throttleLimit < minThrottle)
            {
                limiter       = LimitMode.MinThrottle;
                throttleLimit = (float)minThrottle;
            }

            if (double.IsNaN(throttleLimit))
            {
                throttleLimit = 0;
            }
            throttleLimit = Mathf.Clamp01(throttleLimit);

            vesselState.throttleLimit = throttleLimit;

            if (s.mainThrottle < throttleLimit)
            {
                limiter = LimitMode.None;
            }

            s.mainThrottle = Mathf.Min(s.mainThrottle, throttleLimit);

            if (smoothThrottle)
            {
                s.mainThrottle = SmoothThrottle(s.mainThrottle);
            }

            if (double.IsNaN(s.mainThrottle))
            {
                s.mainThrottle = 0;
            }
            s.mainThrottle = Mathf.Clamp01(s.mainThrottle);

            if (s.Z == 0 && core.rcs.rcsThrottle && vesselState.rcsThrust)
            {
                s.Z = -s.mainThrottle;
            }

            lastThrottle = s.mainThrottle;

            if (!core.attitude.enabled)
            {
                Vector3d act = new Vector3d(s.pitch, s.yaw, s.roll);
                differentialThrottleDemandedTorque = -Vector3d.Scale(act.xzy, vesselState.torqueFromDiffThrottle * s.mainThrottle * 0.5f);
            }
        }
 // Token: 0x06001464 RID: 5220 RVA: 0x00075204 File Offset: 0x00073404
 private IEnumerator StartPageTransition(PageScene newPage, float time)
 {
     newPage.Load();
     if (newPage.HaveMouseOrbitCamera)
     {
         MouseOrbit.Instance.enabled = true;
         Vector3 offset = MouseOrbit.Instance.OrbitOffset;
         Vector3 config = MouseOrbit.Instance.OrbitConfig;
         float   t      = 0f;
         while (t < time && newPage.PageType == MenuPageManager._currentPageType)
         {
             t += Time.deltaTime;
             MouseOrbit.Instance.OrbitConfig    = Vector3.Lerp(config, newPage.MouseOrbitConfig, Mathfx.Ease(t / time, this._transitionType));
             MouseOrbit.Instance.OrbitOffset    = Vector3.Lerp(offset, newPage.MouseOrbitPivot, Mathfx.Ease(t / time, this._transitionType));
             MouseOrbit.Instance.yPanningOffset = Mathf.Lerp(MouseOrbit.Instance.yPanningOffset, 0f, Mathfx.Ease(t / time, this._transitionType));
             yield return(new WaitForEndOfFrame());
         }
         if (newPage.PageType == MenuPageManager._currentPageType)
         {
             MouseOrbit.Instance.OrbitOffset = newPage.MouseOrbitPivot;
             MouseOrbit.Instance.OrbitConfig = newPage.MouseOrbitConfig;
         }
     }
     else
     {
         MouseOrbit.Instance.enabled = false;
     }
     yield break;
 }
    public static void DrawBezier(BezierPoint[] points, float rad, Color col, Texture2D tex)
    {
        rad = Mathf.Round(rad);//It is important to round the numbers otherwise it will mess up with the texture width

        if (points.Length <= 1)
        {
            return;
        }

        Vector2 topleft     = new Vector2(Mathf.Infinity, Mathf.Infinity);
        Vector2 bottomright = new Vector2(0, 0);

        for (int i = 0; i < points.Length - 1; i++)
        {
            Vector2     main     = points[i].main;
            Vector2     control2 = points[i].control2;
            Vector2     control1 = points[i + 1].control1;
            Vector2     main2    = points[i + 1].main;
            BezierCurve curve    = new BezierCurve(main, control2, control1, main2);
            points[i].curve2     = curve;
            points[i + 1].curve1 = curve;

            topleft.x = Mathf.Min(topleft.x, curve.rect.x);

            topleft.y = Mathf.Min(topleft.y, curve.rect.y);

            bottomright.x = Mathf.Max(bottomright.x, curve.rect.x + curve.rect.width);

            bottomright.y = Mathf.Max(bottomright.y, curve.rect.y + curve.rect.height);
        }

        topleft     -= new Vector2(rad, rad);
        bottomright += new Vector2(rad, rad);

        var start = new Vector2(Mathf.Clamp(topleft.x, 0, tex.width), Mathf.Clamp(topleft.y, 0, tex.height));
        var width = new Vector2(Mathf.Clamp(bottomright.x - topleft.x, 0, tex.width - start.x), Mathf.Clamp(bottomright.y - topleft.y, 0, tex.height - start.y));

        Color[] pixels = tex.GetPixels((int)start.x, (int)start.y, (int)width.x, (int)width.y, 0);

        for (var y = 0; y < width.y; y++)
        {
            for (var x = 0; x < width.x; x++)
            {
                var p = new Vector2(x + start.x, y + start.y);
                if (!Mathfx.IsNearBeziers(p, points, rad + 2))
                {
                    continue;
                }

                var samples = Sample(p);
                var c       = Color.black;
                var pc      = pixels[y * (int)width.x + x];//Previous pixel color
                for (var i = 0; i < samples.Length; i++)
                {
                    if (Mathfx.IsNearBeziers(samples[i], points, rad))
                    {
                        c += col;
                    }
                    else
                    {
                        c += pc;
                    }
                }

                c /= samples.Length;

                pixels[y * (int)width.x + x] = c;
            }
        }

        tex.SetPixels((int)start.x, (int)start.y, (int)width.x, (int)width.y, pixels, 0);
        tex.Apply();
    }
Beispiel #11
0
    // Update is called once per frame
    void Update()
    {
        Game.Current.Environment.CurrentMinute += Time.deltaTime * GameSecondsPerMartianMinute;

        if (Game.Current.Environment.CurrentMinute > 60f)
        {
            Game.Current.Environment.CurrentHour++;
            Game.Current.Environment.CurrentMinute = 60f - Game.Current.Environment.CurrentMinute;

            if (OnHourChange != null)
            {
                OnHourChange(Game.Current.Environment.CurrentSol, Game.Current.Environment.CurrentHour);
            }

            if (RunTilMorning && Game.Current.Environment.CurrentHour == 6)
            {
                ToggleSleepUntilMorning(false, PlayerInput.WakeSignal.DayStart);
            }
        }

        if (Game.Current.Environment.CurrentHour > 24 && Game.Current.Environment.CurrentMinute > 40f)
        {
            NewDay();
        }

        float percentOfDay = ((Game.Current.Environment.CurrentHour * 60) + Game.Current.Environment.CurrentMinute) / MartianMinutesPerDay;

        GlobalLight.transform.localRotation = Quaternion.Euler(-90 + (360 * percentOfDay), 0, 0);
        StarsParent.transform.localRotation = GlobalLight.transform.localRotation;

        Game.Current.Environment.Degrees = GetTemperature(percentOfDay);
        GuiBridge.Instance.Temperature.WorldTemperatureText.text = Game.Current.Environment.Degrees.ToString() + "°";

        if (Game.Current.Environment.CurrentHour > 12f)
        {
            GlobalLight.intensity      = Mathf.Max(0f, Mathfx.Hermite(1, MidnightSolarIntensity, (percentOfDay - .5f) * 2));
            GlobalLight.shadowStrength = Mathfx.Hermite(NoonShadowIntensity, 1f, (percentOfDay - .5f) * 2);
            Skybox.SetFloat("_Exposure", Mathf.Max(0f, Mathfx.Hermite(8, -.2f, percentOfDay)));
        }
        else
        {
            GlobalLight.intensity      = Mathf.Max(0f, Mathfx.Hermite(MidnightSolarIntensity, 1f, percentOfDay * 2));
            GlobalLight.shadowStrength = Mathfx.Hermite(1f, NoonShadowIntensity, percentOfDay * 2);
            Skybox.SetFloat("_Exposure", Mathf.Max(0f, Mathfx.Hermite(-.2f, 8f, percentOfDay)));
        }

        if (Game.Current.Environment.CurrentHour > 6 && !dawnMilestone)
        {
            dawnMilestone = true;
            Dawn(true);
        }
        else if (Game.Current.Environment.CurrentHour > 7 && !dawnEnded)
        {
            dawnEnded = true;
            Dawn(false);
        }
        else if (Game.Current.Environment.CurrentHour > 18 && !duskMilestone)
        {
            duskMilestone = true;
            Dusk(true);
        }
        else if (Game.Current.Environment.CurrentHour > 18 && !duskEnded)
        {
            duskEnded = true;
            Dusk(false);
        }

        string textTime = String.Format("M{0}:{1}", ((int)Math.Truncate(Game.Current.Environment.CurrentHour)).ToString("D2"), ((int)Math.Truncate(Game.Current.Environment.CurrentMinute)).ToString("D2"));

        GuiBridge.Instance.TimeText.text = textTime;
        UpdateClocks(textTime);
    }
Beispiel #12
0
        public void BuildContours(float maxError, int maxEdgeLength, VoxelContourSet cset, int buildFlags)
        {
            AstarProfiler.StartProfile("Build Contours");

            AstarProfiler.StartProfile("- Init");
            int w = voxelArea.width;
            int d = voxelArea.depth;

            int wd = w * d;

            //cset.bounds = voxelArea.bounds;

            int maxContours = Mathf.Max(8 /*Max Regions*/, 8);


            //cset.conts = new VoxelContour[maxContours];
            List <VoxelContour> contours = new List <VoxelContour>(maxContours);

            AstarProfiler.EndProfile("- Init");
            AstarProfiler.StartProfile("- Mark Boundaries");

            //cset.nconts = 0;

            //NOTE: This array may contain any data, but since we explicitly set all data in it before we use it, it's OK.
            ushort[] flags = voxelArea.tmpUShortArr;
            if (flags.Length < voxelArea.compactSpanCount)
            {
                flags = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
            }

            // Mark boundaries. (@?)
            for (int z = 0; z < wd; z += voxelArea.width)
            {
                for (int x = 0; x < voxelArea.width; x++)
                {
                    CompactVoxelCell c = voxelArea.compactCells[x + z];

                    for (int i = (int)c.index, ci = (int)(c.index + c.count); i < ci; i++)
                    {
                        ushort           res = 0;
                        CompactVoxelSpan s   = voxelArea.compactSpans[i];

                        if (s.reg == 0 || (s.reg & BorderReg) == BorderReg)
                        {
                            flags[i] = 0;
                            continue;
                        }

                        for (int dir = 0; dir < 4; dir++)
                        {
                            int r = 0;

                            if (s.GetConnection(dir) != NotConnected)
                            {
                                int nx = x + voxelArea.DirectionX[dir];
                                int nz = z + voxelArea.DirectionZ[dir];

                                int ni = (int)voxelArea.compactCells[nx + nz].index + s.GetConnection(dir);
                                r = voxelArea.compactSpans[ni].reg;
                            }

                            //@TODO - Why isn't this inside the previous IF
                            if (r == s.reg)
                            {
                                res |= (ushort)(1 << dir);
                            }
                        }

                        //Inverse, mark non connected edges.
                        flags[i] = (ushort)(res ^ 0xf);
                    }
                }
            }

            AstarProfiler.EndProfile("- Mark Boundaries");

            AstarProfiler.StartProfile("- Simplify Contours");
            List <int> verts = Pathfinding.Util.ListPool <int> .Claim(256);         //new List<int> (256);

            List <int> simplified = Pathfinding.Util.ListPool <int> .Claim(64);     //new List<int> (64);

            for (int z = 0; z < wd; z += voxelArea.width)
            {
                for (int x = 0; x < voxelArea.width; x++)
                {
                    CompactVoxelCell c = voxelArea.compactCells[x + z];

                    for (int i = (int)c.index, ci = (int)(c.index + c.count); i < ci; i++)
                    {
                        //CompactVoxelSpan s = voxelArea.compactSpans[i];

                        if (flags[i] == 0 || flags[i] == 0xf)
                        {
                            flags[i] = 0;
                            continue;
                        }

                        int reg = voxelArea.compactSpans[i].reg;

                        if (reg == 0 || (reg & BorderReg) == BorderReg)
                        {
                            continue;
                        }

                        int area = voxelArea.areaTypes[i];

                        verts.Clear();
                        simplified.Clear();

                        WalkContour(x, z, i, flags, verts);

                        SimplifyContour(verts, simplified, maxError, maxEdgeLength, buildFlags);
                        RemoveDegenerateSegments(simplified);

                        VoxelContour contour = new VoxelContour();
                        contour.verts = ClaimIntArr(simplified.Count, false);                       //simplified.ToArray ();
                        for (int j = 0; j < simplified.Count; j++)
                        {
                            contour.verts[j] = simplified[j];
                        }
#if ASTAR_RECAST_INCLUDE_RAW_VERTEX_CONTOUR
                        //Not used at the moment, just debug stuff
                        contour.rverts = ClaimIntArr(verts.Count);
                        for (int j = 0; j < verts.Count; j++)
                        {
                            contour.rverts[j] = verts[j];
                        }
#endif
                        contour.nverts = simplified.Count / 4;
                        contour.reg    = reg;
                        contour.area   = area;

                        contours.Add(contour);

                                                #if ASTARDEBUG
                        for (int q = 0, j = (simplified.Count / 4) - 1; q < (simplified.Count / 4); j = q, q++)
                        {
                            int i4 = q * 4;
                            int j4 = j * 4;

                            Vector3 p1 = Vector3.Scale(
                                new Vector3(
                                    simplified[i4 + 0],
                                    simplified[i4 + 1],
                                    (simplified[i4 + 2] / (float)voxelArea.width)
                                    ),
                                cellScale)
                                         + voxelOffset;

                            Vector3 p2 = Vector3.Scale(
                                new Vector3(
                                    simplified[j4 + 0],
                                    simplified[j4 + 1],
                                    (simplified[j4 + 2] / (float)voxelArea.width)
                                    )
                                , cellScale)
                                         + voxelOffset;


                            if (CalcAreaOfPolygon2D(contour.verts, contour.nverts) > 0)
                            {
                                Debug.DrawLine(p1, p2, Mathfx.IntToColor(reg, 0.5F));
                            }
                            else
                            {
                                Debug.DrawLine(p1, p2, Color.red);
                            }
                        }
                                                #endif
                    }
                }
            }

            Pathfinding.Util.ListPool <int> .Release(verts);

            Pathfinding.Util.ListPool <int> .Release(simplified);

            AstarProfiler.EndProfile("- Simplify Contours");

            AstarProfiler.StartProfile("- Fix Contours");

            // Check and merge droppings.
            // Sometimes the previous algorithms can fail and create several contours
            // per area. This pass will try to merge the holes into the main region.
            for (int i = 0; i < contours.Count; i++)
            {
                VoxelContour cont = contours[i];
                // Check if the contour is would backwards.
                if (CalcAreaOfPolygon2D(cont.verts, cont.nverts) < 0)
                {
                    // Find another contour which has the same region ID.
                    int mergeIdx = -1;
                    for (int j = 0; j < contours.Count; j++)
                    {
                        if (i == j)
                        {
                            continue;
                        }
                        if (contours[j].nverts > 0 && contours[j].reg == cont.reg)
                        {
                            // Make sure the polygon is correctly oriented.
                            if (CalcAreaOfPolygon2D(contours[j].verts, contours[j].nverts) > 0)
                            {
                                mergeIdx = j;
                                break;
                            }
                        }
                    }
                    if (mergeIdx == -1)
                    {
                        Debug.LogError("rcBuildContours: Could not find merge target for bad contour " + i + ".");
                    }
                    else
                    {
                        // Debugging
                        //Debug.LogWarning ("Fixing contour");

                        VoxelContour mcont = contours[mergeIdx];
                        // Merge by closest points.
                        int ia = 0, ib = 0;
                        GetClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ref ia, ref ib);

                        if (ia == -1 || ib == -1)
                        {
                            Debug.LogWarning("rcBuildContours: Failed to find merge points for " + i + " and " + mergeIdx + ".");
                            continue;
                        }

#if ASTARDEBUG
                        int p4  = ia * 4;
                        int p42 = ib * 4;

                        Vector3 p12 = Vector3.Scale(
                            new Vector3(
                                mcont.verts[p4 + 0],
                                mcont.verts[p4 + 1],
                                (mcont.verts[p4 + 2] / (float)voxelArea.width)
                                ),
                            cellScale)
                                      + voxelOffset;

                        Vector3 p22 = Vector3.Scale(
                            new Vector3(
                                cont.verts[p42 + 0],
                                cont.verts[p42 + 1],
                                (cont.verts[p42 + 2] / (float)voxelArea.width)
                                )
                            , cellScale)
                                      + voxelOffset;

                        Debug.DrawLine(p12, p22, Color.green);
#endif

                        if (!MergeContours(ref mcont, ref cont, ia, ib))
                        {
                            Debug.LogWarning("rcBuildContours: Failed to merge contours " + i + " and " + mergeIdx + ".");
                            continue;
                        }

                        contours[mergeIdx] = mcont;
                        contours[i]        = cont;

                                                #if ASTARDEBUG
                        Debug.Log(mcont.nverts);

                        for (int q = 0, j = (mcont.nverts) - 1; q < (mcont.nverts); j = q, q++)
                        {
                            int i4 = q * 4;
                            int j4 = j * 4;

                            Vector3 p1 = Vector3.Scale(
                                new Vector3(
                                    mcont.verts[i4 + 0],
                                    mcont.verts[i4 + 1],
                                    (mcont.verts[i4 + 2] / (float)voxelArea.width)
                                    ),
                                cellScale)
                                         + voxelOffset;

                            Vector3 p2 = Vector3.Scale(
                                new Vector3(
                                    mcont.verts[j4 + 0],
                                    mcont.verts[j4 + 1],
                                    (mcont.verts[j4 + 2] / (float)voxelArea.width)
                                    )
                                , cellScale)
                                         + voxelOffset;

                            Debug.DrawLine(p1, p2, Color.red);
                            //}
                        }
                                                #endif
                    }
                }
            }

            cset.conts = contours;

            AstarProfiler.EndProfile("- Fix Contours");

            AstarProfiler.EndProfile("Build Contours");
        }
Beispiel #13
0
    protected void SetCoarse()
    {
        if (transform.eulerAngles.z % 45 == 0)
        {
            mover.SetDirection((int)(transform.eulerAngles.z / 45));
            mover.Mobilize(mover.speed);
        }

        var rb = GetComponent <Rigidbody2D>();

        if (!rb)
        {
            Debug.LogWarning("No Rigid Body Found.");
            return;
        }
        var contacts = new Collider2D[50];
        var count    = rb.GetContacts(contacts);

        System.Array.Resize(ref contacts, count);

        var sectors = new List <SectorHandler>();

        for (int i = 0; i < contacts.Length; i++)
        {
            var sector = contacts[i].GetComponent <SectorHandler>();
            if (sector)
            {
                sectors.Add(sector);
            }
        }

        if (sectors.Count == 0)
        {
            return;
        }

        SectorHandler sect = sectors[0];

        for (int i = 1; i < sectors.Count; i++)
        {
            if (Mathf.Abs(sectors[i].transform.eulerAngles.z - transform.eulerAngles.z) < Mathf.Abs(sect.transform.eulerAngles.z - transform.eulerAngles.z))
            {
                sect = sectors[i];
            }
        }

        int direction = 0;

        if (sect.transform.eulerAngles.z >= 0)
        {
            direction = (int)(sect.transform.eulerAngles.z / 45f);
        }
        else
        {
            direction = (int)(360 + sect.transform.eulerAngles.z / 45f);
        }
        mover.SetDirection(direction);
        mover.Mobilize(mover.speed);
        transform.eulerAngles = sect.transform.eulerAngles;
        var radius = Vector3.Distance(transform.position, Vector3.zero) + 0.5f;
        var coarse = Mathfx.GetPointOnCircle(radius, (direction * 45) + 90, Vector3.zero);

        mover.StartMovement(MoveType.Detour, 3, coarse);
    }
Beispiel #14
0
    override public void Update()
    {
        //if (m_Human.PlayerProperty != null)

        //Debug.Log(Time.timeSinceLevelLoad + " " + this.ToString() + " - update " + State.ToString() + " " + EndOfStateTime);
        UpdateFinalRotation();

        if (RotationOk == false)
        {
            CurrentRotationTime += Time.deltaTime;

            if (CurrentRotationTime >= RotationTime)
            {
                CurrentRotationTime = RotationTime;
                RotationOk          = true;
            }

            float      progress = CurrentRotationTime / RotationTime;
            Quaternion q        = Quaternion.Lerp(StartRotation, FinalRotation, progress);
            Owner.Transform.rotation = q;
        }

        if (PositionOK == false)
        {
            CurrentMoveTime += Time.deltaTime;
            if (CurrentMoveTime >= MoveTime)
            {
                CurrentMoveTime = MoveTime;
                PositionOK      = true;
            }

            float   progress = CurrentMoveTime / MoveTime;
            Vector3 finalPos = Mathfx.Sinerp(StartPosition, FinalPosition, progress);
            //MoveTo(finalPos);
            if (Move(finalPos - Transform.position) == false)
            {
                PositionOK = true;
            }
        }

        switch (State)
        {
        case E_State.E_START:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                InitializeBlockLoop();
            }
            break;

        case E_State.E_BLOCK:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                InitializeBlockEnd();
            }
            Move(MoveDir.normalized / 2);
            break;

        case E_State.E_BLOCK_HIT:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                if (Time.timeSinceLevelLoad < BlockEndTime)
                {
                    InitializeBlockLoop();
                }
                else
                {
                    InitializeBlockEnd();
                }

                if (ActionDamageBlocked != null)
                {
                    ActionDamageBlocked.SetSuccess();
                    ActionDamageBlocked = null;
                }
            }
            break;

        case E_State.E_END:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                Release();
            }
            break;
        }
    }
Beispiel #15
0
 public static Vector2 Hermite(Vector2 start, Vector2 end, float t)
 {
     return(new Vector2(Mathfx.Hermite(start.x, end.x, t), Mathfx.Hermite(start.y, end.y, t)));
 }
Beispiel #16
0
 public static Vector3 Hermite(Vector3 start, Vector3 end, float t)
 {
     return(new Vector3(Mathfx.Hermite(start.x, end.x, t), Mathfx.Hermite(start.y, end.y, t), Mathfx.Hermite(start.z, end.z, t)));
 }
 private void Update()
 {
     _animator.SetFloat(kAnimLocomotionSpeed, Mathfx.Damp(_animator.GetFloat(kAnimLocomotionSpeed), (float)_currentLocomotionSpeed, 0.25f, Time.deltaTime * 5));
     _animator.SetFloat(kAnimLocomotionState, Mathfx.Damp(_animator.GetFloat(kAnimLocomotionState), (float)_currentLocomotionState, 0.25f, Time.deltaTime * 5));
 }
Beispiel #18
0
    public bool RunFunnel(List <Vector3> left, List <Vector3> right, List <Vector3> funnelPath)
    {
        if (left.Count <= 3)
        {
            return(false);
        }

        System.Console.WriteLine("Start");

        //Remove identical vertices
        while (left[1] == left[2] && right[1] == right[2])
        {
            System.Console.WriteLine("Removing identical left and right");
            left.RemoveAt(1);
            right.RemoveAt(1);
        }

        /*while (right[1] == right[2]) {
         *      System.Console.WriteLine ("Removing identical right");
         *      right.RemoveAt (1);
         *      left.RemoveAt (1);
         * }*/

        Vector3 swPoint = left[2];

        if (swPoint == left[1])
        {
            swPoint = right[2];
        }

        /*if (Polygon.IsColinear (left[0],left[1],right[1])) {
         *      System.Console.WriteLine ("	Colinear");
         *      left[0] += (left[2]-left[0]).normalized*0.001F;
         *      if (Polygon.IsColinear (left[0],left[1],right[1])) {
         *              Debug.LogError ("WUT!!!");//NOTE - CAN ACTUALLY HAPPEN!
         *      }
         * }*/


        //Solves cases where the start point lies on the wrong side of the first funnel portal
        if (Polygon.IsColinear(left[0], left[1], right[1]) || Polygon.Left(left[1], right[1], swPoint) == Polygon.Left(left[1], right[1], left[0]))
        {
            Debug.DrawLine(left[1], right[1], new Color(0, 0, 0, 0.5F));
            Debug.DrawLine(left[0], swPoint, new Color(0, 0, 0, 0.5F));
            System.Console.WriteLine("Wrong Side");
            left[0]  = Mathfx.NearestPointStrict(left[1], right[1], left[0]);
            left[0] += (left[0] - swPoint).normalized * 0.001F;        //Tiny move to the right side to prevent floating point errors, too bad with that .normalized call though, could perhaps be optimized
            right[0] = left[0];
        }

        //Switch left and right to really be on the "left" and "right" sides
        if (!Polygon.IsClockwise(left[0], left[1], right[1]) && !Polygon.IsColinear(left[0], left[1], right[1]))
        {
            System.Console.WriteLine("Wrong Side 2");
            List <Vector3> tmp = left;
            left  = right;
            right = tmp;
        }

        /*for (int i=1;i<leftFunnel.Length-1;i++) {
         *
         *      float unitWidth = 5;
         *      Int3 normal = (rightFunnel[i]-leftFunnel[i]);
         *      float magn = normal.worldMagnitude;
         *      normal /= magn;
         *      normal *= Mathf.Clamp (unitWidth,0,(magn/2F));
         *      leftFunnel[i] += normal;
         *      rightFunnel[i] -= normal;
         * }*/


        funnelPath.Add(left[0]);

        Vector3 portalApex  = left[0];
        Vector3 portalLeft  = left[1];
        Vector3 portalRight = right[1];

        int apexIndex  = 0;
        int rightIndex = 1;
        int leftIndex  = 1;

        //yield return 0;

        for (int i = 2; i < left.Count; i++)
        {
            if (funnelPath.Count > 200)
            {
                Debug.LogWarning("Avoiding infinite loop");
                break;
            }

            Vector3 pLeft  = left[i];
            Vector3 pRight = right[i];

            /*Debug.DrawLine (portalApex,portalLeft,Color.red);
             * Debug.DrawLine (portalApex,portalRight,Color.yellow);
             * Debug.DrawLine (portalApex,left,Color.cyan);
             * Debug.DrawLine (portalApex,right,Color.cyan);*/

            if (Polygon.TriangleArea2(portalApex, portalRight, pRight) >= 0)
            {
                if (portalApex == portalRight || Polygon.TriangleArea2(portalApex, portalLeft, pRight) <= 0)
                {
                    portalRight = pRight;
                    rightIndex  = i;
                }
                else
                {
                    funnelPath.Add(portalLeft);
                    portalApex = portalLeft;
                    apexIndex  = leftIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            if (Polygon.TriangleArea2(portalApex, portalLeft, pLeft) <= 0)
            {
                if (portalApex == portalLeft || Polygon.TriangleArea2(portalApex, portalRight, pLeft) >= 0)
                {
                    portalLeft = pLeft;
                    leftIndex  = i;
                }
                else
                {
                    funnelPath.Add(portalRight);
                    portalApex = portalRight;
                    apexIndex  = rightIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            //yield return 0;
        }

        //yield return 0;

        funnelPath.Add(left[left.Count - 1]);
        return(true);
    }
    public static Texture2D DrawLine(Vector2 from, Vector2 to, float w, Color col, Texture2D tex, bool stroke, Color strokeCol, float strokeWidth)
    {
        w           = Mathf.Round(w);//It is important to round the numbers otherwise it will mess up with the texture width
        strokeWidth = Mathf.Round(strokeWidth);

        var extent = w + strokeWidth;
        var stY    = Mathf.Clamp(Mathf.Min(from.y, to.y) - extent, 0, tex.height);//This is the topmost Y value
        var stX    = Mathf.Clamp(Mathf.Min(from.x, to.x) - extent, 0, tex.width);
        var endY   = Mathf.Clamp(Mathf.Max(from.y, to.y) + extent, 0, tex.height);
        var endX   = Mathf.Clamp(Mathf.Max(from.x, to.x) + extent, 0, tex.width);//This is the rightmost Y value

        strokeWidth = strokeWidth / 2;
        var strokeInner  = (w - strokeWidth) * (w - strokeWidth);
        var strokeOuter  = (w + strokeWidth) * (w + strokeWidth);
        var strokeOuter2 = (w + strokeWidth + 1) * (w + strokeWidth + 1);
        var sqrW         = w * w;//It is much faster to calculate with squared values

        var lengthX = endX - stX;
        var lengthY = endY - stY;
        var start   = new Vector2(stX, stY);

        Color[] pixels = tex.GetPixels((int)stX, (int)stY, (int)lengthX, (int)lengthY, 0);//Get all pixels

        for (int y = 0; y < lengthY; y++)
        {
            for (int x = 0; x < lengthX; x++)
            {//Loop through the pixels
                var   p      = new Vector2(x, y) + start;
                var   center = p + new Vector2(0.5f, 0.5f);
                float dist   = (center - Mathfx.NearestPointStrict(from, to, center)).sqrMagnitude;//The squared distance from the center of the pixels to the nearest point on the line
                if (dist <= strokeOuter2)
                {
                    var samples = Sample(p);
                    var c       = Color.black;
                    var pc      = pixels[y * (int)lengthX + x];
                    for (int i = 0; i < samples.Length; i++)
                    {                                                                                       //Loop through the samples
                        dist = (samples[i] - Mathfx.NearestPointStrict(from, to, samples[i])).sqrMagnitude; //The squared distance from the sample to the line
                        if (stroke)
                        {
                            if (dist <= strokeOuter && dist >= strokeInner)
                            {
                                c += strokeCol;
                            }
                            else if (dist < sqrW)
                            {
                                c += col;
                            }
                            else
                            {
                                c += pc;
                            }
                        }
                        else
                        {
                            if (dist < sqrW)
                            {//Is the distance smaller than the width of the line
                                c += col;
                            }
                            else
                            {
                                c += pc;//No it wasn't, set it to be the original colour
                            }
                        }
                    }
                    c /= samples.Length;//Get the avarage colour
                    pixels[y * (int)lengthX + x] = c;
                }
            }
        }
        tex.SetPixels((int)stX, (int)stY, (int)lengthX, (int)lengthY, pixels, 0);
        tex.Apply();
        return(tex);
    }
    // Token: 0x06001BC2 RID: 7106 RVA: 0x0008E1EC File Offset: 0x0008C3EC
    public override void UpdateTouches(Touch touch)
    {
        if (this.finger.FingerId != -1 && touch.fingerId != this.finger.FingerId)
        {
            return;
        }
        if (this.finger.FingerId == -1 && touch.phase != TouchPhase.Began)
        {
            return;
        }
        Vector2 vector = touch.position;

        if (this._rotationAngle != 0f)
        {
            vector = Mathfx.RotateVector2AboutPoint(touch.position, new Vector2(this._rotationPoint.x, (float)Screen.height - this._rotationPoint.y), -this._rotationAngle);
        }
        switch (touch.phase)
        {
        case TouchPhase.Began:
            if (this.TouchInside(vector))
            {
                this.finger.StartPos       = vector;
                this.finger.LastPos        = vector;
                this.finger.StartTouchTime = Time.time;
                this.finger.FingerId       = touch.fingerId;
                this._inside = true;
                if (this.OnTouchBegan != null)
                {
                    this.OnTouchBegan(vector);
                }
            }
            break;

        case TouchPhase.Moved:
        case TouchPhase.Stationary:
        {
            bool flag = this.TouchInside(vector);
            if (this._inside && !flag)
            {
                this._inside = false;
                if (this.OnTouchLeftBoundary != null)
                {
                    this.OnTouchLeftBoundary(vector, touch.deltaPosition);
                }
            }
            else if (!this._inside && flag)
            {
                this._inside = true;
                if (this.OnTouchEnteredBoundary != null)
                {
                    this.OnTouchEnteredBoundary(vector, touch.deltaPosition);
                }
            }
            if (this.OnTouchMoved != null)
            {
                this.OnTouchMoved(vector, touch.deltaPosition);
            }
            this.finger.LastPos = vector;
            break;
        }

        case TouchPhase.Ended:
        case TouchPhase.Canceled:
            if (this.OnTouchEnded != null)
            {
                this.OnTouchEnded(vector);
            }
            this.ResetTouch();
            break;
        }
    }
    /*public override void ApplyOriginal (Path p) {
     *
     *      if (exactStartPoint) {
     *              pStart = GetClampedPoint (p.path[0].position, p.originalStartPoint, p.path[0]);
     *
     *              if (!addPoints) {
     *                      p.startPoint = pStart;
     *              }
     *      }
     *
     *      if (exactEndPoint) {
     *              pEnd = GetClampedPoint (p.path[p.path.Length-1].position, p.originalEndPoint, p.path[p.path.Length-1]);
     *
     *              if (!addPoints) {
     *                      p.endPoint = pEnd;
     *              }
     *      }
     * }*/

    public override void Apply(Path _p, ModifierData source)
    {
        ABPath p = _p as ABPath;

        //Only for ABPaths
        if (p == null)
        {
            return;
        }

        if (p.vectorPath.Count == 0)
        {
            return;
        }
        else if (p.vectorPath.Count < 2 && !addPoints)
        {
            //Vector3[] arr = new Vector3[2];
            //arr[0] = p.vectorPath[0];
            //arr[1] = p.vectorPath[0];
            //p.vectorPath = arr;
            p.vectorPath.Add(p.vectorPath[0]);
        }

        //Debug.DrawRay (p.originalEndPoint,Vector3.up,Color.red);
        //Debug.DrawRay (p.startPoint,Vector3.up,Color.red);
        //Debug.DrawRay (p.endPoint,Vector3.up,Color.green);

        Vector3 pStart = Vector3.zero,
                pEnd   = Vector3.zero;

        if (exactStartPoint == Exactness.Original)
        {
            pStart = GetClampedPoint((Vector3)p.path[0].position, p.originalStartPoint, p.path[0]);
        }
        else if (exactStartPoint == Exactness.ClosestOnNode)
        {
            pStart = GetClampedPoint((Vector3)p.path[0].position, p.startPoint, p.path[0]);
        }
        else if (exactStartPoint == Exactness.Interpolate)
        {
            pStart = GetClampedPoint((Vector3)p.path[0].position, p.originalStartPoint, p.path[0]);
            pStart = Mathfx.NearestPointStrict((Vector3)p.path[0].position, (Vector3)p.path[1 >= p.path.Count?0:1].position, pStart);
        }
        else
        {
            pStart = (Vector3)p.path[0].position;
        }

        if (exactEndPoint == Exactness.Original)
        {
            pEnd = GetClampedPoint((Vector3)p.path[p.path.Count - 1].position, p.originalEndPoint, p.path[p.path.Count - 1]);
        }
        else if (exactEndPoint == Exactness.ClosestOnNode)
        {
            pEnd = GetClampedPoint((Vector3)p.path[p.path.Count - 1].position, p.endPoint, p.path[p.path.Count - 1]);
        }
        else if (exactEndPoint == Exactness.Interpolate)
        {
            pEnd = GetClampedPoint((Vector3)p.path[p.path.Count - 1].position, p.originalEndPoint, p.path[p.path.Count - 1]);

            pEnd = Mathfx.NearestPointStrict((Vector3)p.path[p.path.Count - 1].position, (Vector3)p.path[p.path.Count - 2 < 0?0:p.path.Count - 2].position, pEnd);
        }
        else
        {
            pEnd = (Vector3)p.path[p.path.Count - 1].position;
        }

        if (!addPoints)
        {
            //p.vectorPath[0] = p.startPoint;
            //p.vectorPath[p.vectorPath.Length-1] = p.endPoint;
            //Debug.DrawLine (p.vectorPath[0],pStart,Color.green);
            //Debug.DrawLine (p.vectorPath[p.vectorPath.Length-1],pEnd,Color.green);
            p.vectorPath[0] = pStart;
            p.vectorPath[p.vectorPath.Count - 1] = pEnd;
        }
        else
        {
            //Vector3[] newPath = new Vector3[p.vectorPath.Length+(exactStartPoint != Exactness.SnapToNode ? 1 : 0) + (exactEndPoint  != Exactness.SnapToNode ? 1 : 0)];

            if (exactEndPoint != Exactness.SnapToNode)
            {
                //newPath[0] = pStart;
                p.vectorPath.Insert(0, pStart);
            }

            if (exactEndPoint != Exactness.SnapToNode)
            {
                //newPath[newPath.Length-1] = pEnd;
                p.vectorPath.Add(pEnd);
            }

            /*int offset = exactStartPoint != Exactness.SnapToNode ? 1 : 0;
             * for (int i=0;i<p.vectorPath.Length;i++) {
             *      newPath[i+offset] = p.vectorPath[i];
             * }
             * p.vectorPath = newPath;*/
        }
    }
Beispiel #22
0
        public override void Drive(FlightCtrlState s)
        {
            float threshold = 0.1F;
            bool  _userCommandingRotation = !(Mathfx.Approx(s.pitch, s.pitchTrim, threshold) &&
                                              Mathfx.Approx(s.yaw, s.yawTrim, threshold) &&
                                              Mathfx.Approx(s.roll, s.rollTrim, threshold));
            bool _userCommandingTranslation = !(Math.Abs(s.X) < threshold &&
                                                Math.Abs(s.Y) < threshold &&
                                                Math.Abs(s.Z) < threshold);

            if (_userCommandingRotation && !_userCommandingTranslation)
            {
                userCommandingRotationSmoothed = 2;
            }
            else if (userCommandingRotationSmoothed > 0)
            {
                userCommandingRotationSmoothed--;
            }

            if (core.GetComputerModule <MechJebModuleThrustWindow>().hidden&& core.GetComputerModule <MechJebModuleAscentGuidance>().hidden)
            {
                return;
            }

            if ((tmode != TMode.OFF) && (vesselState.thrustAvailable > 0))
            {
                double spd = 0;

                switch (tmode)
                {
                case TMode.KEEP_ORBITAL:
                    spd = vesselState.speedOrbital;
                    break;

                case TMode.KEEP_SURFACE:
                    spd = vesselState.speedSurface;
                    break;

                case TMode.KEEP_VERTICAL:
                    spd = vesselState.speedVertical;
                    Vector3d rot = Vector3d.up;
                    if (trans_kill_h)
                    {
                        Vector3 hsdir = Vector3.ProjectOnPlane(vesselState.surfaceVelocity, vesselState.up);
                        Vector3 dir   = -hsdir + vesselState.up * Math.Max(Math.Abs(spd), 20 * mainBody.GeeASL);
                        if ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) > 5000) && (hsdir.magnitude > Math.Max(Math.Abs(spd), 100 * mainBody.GeeASL) * 2))
                        {
                            tmode         = TMode.DIRECT;
                            trans_spd_act = 100;
                            rot           = -hsdir;
                        }
                        else
                        {
                            rot = dir.normalized;
                        }
                        core.attitude.attitudeTo(rot, AttitudeReference.INERTIAL, null);
                    }
                    break;
                }

                double t_err = (trans_spd_act - spd) / vesselState.maxThrustAccel;
                if ((tmode == TMode.KEEP_ORBITAL && Vector3d.Dot(vesselState.forward, vesselState.orbitalVelocity) < 0) ||
                    (tmode == TMode.KEEP_SURFACE && Vector3d.Dot(vesselState.forward, vesselState.surfaceVelocity) < 0))
                {
                    //allow thrust to declerate
                    t_err *= -1;
                }

                double t_act = pid.Compute(t_err);

                if ((tmode != TMode.KEEP_VERTICAL) ||
                    !trans_kill_h ||
                    (core.attitude.attitudeError < 2) ||
                    ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) < 1000) && (core.attitude.attitudeError < 90)))
                {
                    if (tmode == TMode.DIRECT)
                    {
                        trans_prev_thrust = targetThrottle = trans_spd_act / 100.0F;
                    }
                    else
                    {
                        trans_prev_thrust = targetThrottle = Mathf.Clamp01(trans_prev_thrust + (float)t_act);
                    }
                }
                else
                {
                    bool useGimbal = (vesselState.torqueGimbal.positive.x > vesselState.torqueAvailable.x * 10) ||
                                     (vesselState.torqueGimbal.positive.z > vesselState.torqueAvailable.z * 10);

                    bool useDiffThrottle = (vesselState.torqueDiffThrottle.x > vesselState.torqueAvailable.x * 10) ||
                                           (vesselState.torqueDiffThrottle.z > vesselState.torqueAvailable.z * 10);

                    if ((core.attitude.attitudeError >= 2) && (useGimbal || (useDiffThrottle && core.thrust.differentialThrottle)))
                    {
                        trans_prev_thrust = targetThrottle = 0.1F;
                        print(" targetThrottle = 0.1F");
                    }
                    else
                    {
                        trans_prev_thrust = targetThrottle = 0;
                    }
                }
            }

            // Only set throttle if a module need it. Otherwise let the user or other mods set it
            // There is always at least 1 user : the module itself (why ?)
            if (users.Count > 1)
            {
                s.mainThrottle = targetThrottle;
            }

            throttleLimit      = 1;
            throttleFixedLimit = 1;

            limiter = LimitMode.None;

            if (limitThrottle)
            {
                if (maxThrottle < throttleLimit)
                {
                    setFixedLimit((float)maxThrottle, LimitMode.Throttle);
                }
            }

            if (limitToTerminalVelocity)
            {
                float limit = TerminalVelocityThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.TerminalVelocity);
                }
            }

            if (limitDynamicPressure)
            {
                float limit = MaximumDynamicPressureThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.DynamicPressure);
                }
            }

            if (limitToPreventOverheats)
            {
                float limit = (float)TemperatureSafetyThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.Temperature);
                }
            }

            if (limitAcceleration)
            {
                float limit = AccelerationLimitedThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.Acceleration);
                }
            }

            if (electricThrottle && ElectricEngineRunning())
            {
                float limit = ElectricThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.Electric);
                }
            }

            if (limitToPreventFlameout)
            {
                // This clause benefits being last: if we don't need much air
                // due to prior limits, we can close some intakes.
                float limit = FlameoutSafetyThrottle();
                if (limit < throttleLimit)
                {
                    setFixedLimit(limit, LimitMode.Flameout);
                }
            }

            // Any limiters which can limit to non-zero values must come before this, any
            // limiters (like ullage) which enforce zero throttle should come after.  The
            // minThrottle setting has authority over any other limiter that sets non-zero throttle.
            if (limiterMinThrottle && limiter != LimitMode.None)
            {
                if (minThrottle > throttleFixedLimit)
                {
                    setFixedLimit((float)minThrottle, LimitMode.MinThrottle);
                }
                if (minThrottle > throttleLimit)
                {
                    setTempLimit((float)minThrottle, LimitMode.MinThrottle);
                }
            }

            /* auto-RCS ullaging up to very stable */
            if (autoRCSUllaging && s.mainThrottle > 0.0F && throttleLimit > 0.0F)
            {
                if (vesselState.lowestUllage < VesselState.UllageState.VeryStable)
                {
                    Debug.Log("MechJeb RCS auto-ullaging: found state below very stable: " + vesselState.lowestUllage);
                    if (vessel.hasEnabledRCSModules())
                    {
                        if (!vessel.ActionGroups[KSPActionGroup.RCS])
                        {
                            Debug.Log("MechJeb RCS auto-ullaging: enabling RCS action group for automatic ullaging");
                            vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true);
                        }
                        Debug.Log("MechJeb RCS auto-ullaging: firing RCS to stabilize ulllage");
                        setTempLimit(0.0F, LimitMode.UnstableIgnition);
                        s.Z = -1.0F;
                    }
                    else
                    {
                        Debug.Log("MechJeb RCS auto-ullaging: vessel has no enabled/staged RCS modules");
                    }
                }
            }

            /* prevent unstable ignitions */
            if (limitToPreventUnstableIgnition && s.mainThrottle > 0.0F && throttleLimit > 0.0F)
            {
                if (vesselState.lowestUllage < VesselState.UllageState.Stable)
                {
                    ScreenMessages.PostScreenMessage(preventingUnstableIgnitionsMessage);
                    Debug.Log("MechJeb Unstable Ignitions: preventing ignition in state: " + vesselState.lowestUllage);
                    setTempLimit(0.0F, LimitMode.UnstableIgnition);
                }
            }

            // we have to force the throttle here so that rssMode can work, otherwise we don't get our last throttle command
            // back on the next tick after disabling.  we save this before applying the throttle limits so that we preserve
            // the requested throttle, and not the limited throttle.
            if (core.rssMode)
            {
                SetFlightGlobals(s.mainThrottle);
            }

            if (double.IsNaN(throttleLimit))
            {
                throttleLimit = 1.0F;
            }
            throttleLimit = Mathf.Clamp01(throttleLimit);

            /* we do not _apply_ the "fixed" limit, the actual throttleLimit should always be the more limited and lower one */
            /* the purpose of the "fixed" limit is for external consumers like the node executor to consume */
            if (double.IsNaN(throttleFixedLimit))
            {
                throttleFixedLimit = 1.0F;
            }
            throttleFixedLimit = Mathf.Clamp01(throttleFixedLimit);

            vesselState.throttleLimit      = throttleLimit;
            vesselState.throttleFixedLimit = throttleFixedLimit;

            if (s.mainThrottle < throttleLimit)
            {
                limiter = LimitMode.None;
            }

            s.mainThrottle = Mathf.Min(s.mainThrottle, throttleLimit);

            if (smoothThrottle)
            {
                s.mainThrottle = SmoothThrottle(s.mainThrottle);
            }

            if (double.IsNaN(s.mainThrottle))
            {
                s.mainThrottle = 0;
            }

            s.mainThrottle = Mathf.Clamp01(s.mainThrottle);


            if (s.Z == 0 && core.rcs.rcsThrottle && vesselState.rcsThrust)
            {
                s.Z = -s.mainThrottle;
            }

            lastThrottle = s.mainThrottle;

            if (!core.attitude.enabled)
            {
                Vector3d act = new Vector3d(s.pitch, s.yaw, s.roll);
                differentialThrottleDemandedTorque = -Vector3d.Scale(act.xzy, vesselState.torqueDiffThrottle * s.mainThrottle * 0.5f);
            }
        }
Beispiel #23
0
 void FixedUpdate()
 {
     transform.position = Mathfx.Bounce(transform.position);
 }
Beispiel #24
0
    /** Applies constrained movement from \a startPos to \a endPos.
     * The result is stored in \a clampedPos.
     * Returns the new current node */
    public GraphNode ClampAlongNavmesh(Vector3 startPos, GraphNode _startNode, Vector3 endPos, out Vector3 clampedPos)
    {
        ConvexMeshNode startNode = (ConvexMeshNode)_startNode;

        clampedPos = endPos;

        Stack <ConvexMeshNode> stack  = tmpStack;               // Tiny stack
        List <ConvexMeshNode>  closed = tmpClosed;              // Tiny closed list

        stack.Clear();
        closed.Clear();

        Vector3        bestPos, p;
        float          bestDist = float.PositiveInfinity;
        float          d;
        ConvexMeshNode bestRef = null;
        // Search constraint
        Vector3 searchPos    = (startPos + endPos) / 2;
        float   searchRadius = Mathfx.MagnitudeXZ(startPos, endPos) / 2;

        // Init
        bestPos = startPos;
        stack.Push(startNode);
        closed.Add(startNode);         // Self ref, start maker.

        INavmesh graph = AstarData.GetGraph(startNode) as INavmesh;

        if (graph == null)
        {
            //Debug.LogError ("Null graph, or the graph was no NavMeshGraph");
            return(startNode);
        }

#if ASTARDEBUG
        Debug.DrawLine(startPos, endPos, Color.blue);
#endif

        while (stack.Count > 0)
        {
            // Pop front.
            ConvexMeshNode cur = stack.Pop();

            // If target is inside the cur, stop search.
            if (NavMeshGraph.ContainsPoint(cur, endPos, graph.vertices))
            {
#if ASTARDEBUG
                Debug.DrawRay(endPos, Vector3.up, Color.red);
#endif
                bestRef = cur;
                bestPos = endPos;
                break;
            }
            // Follow edges or keep track of nearest point on blocking edge.
            for (int i = 0, j = 2; i < 3; j = i++)
            {
                int sp = cur.GetVertexIndex(j);
                int sq = cur.GetVertexIndex(i);

                bool           blocking = true;
                ConvexMeshNode conn     = null;

                for (int q = 0; q < cur.connections.Length; q++)
                {
                    conn = cur.connections[q] as ConvexMeshNode;
                    if (conn == null)
                    {
                        continue;
                    }

                    for (int i2 = 0, j2 = 2; i2 < 3; j2 = i2++)
                    {
                        int sp2 = conn.GetVertexIndex(j2);
                        int sq2 = conn.GetVertexIndex(i2);
                        if ((sp2 == sp && sq2 == sq) || (sp2 == sq && sq2 == sp))
                        {
                            blocking = false;
                            break;
                        }
                    }

                    if (!blocking)
                    {
                        break;
                    }
                }

                //Node neiRef = cur->nei[j];

                if (blocking)
                {
                    // Blocked edge, calc distance.
                    p = Mathfx.NearestPointStrictXZ((Vector3)graph.vertices[sp], (Vector3)graph.vertices[sq], endPos);

#if ASTARDEBUG
                    Debug.DrawLine((Vector3)graph.vertices[sp] + Vector3.up * 0.1F, (Vector3)graph.vertices[sq] + Vector3.up * 0.1F, Color.black);
#endif
                    d = Mathfx.MagnitudeXZ(p, endPos);
                    if (d < bestDist)
                    {
                        // Update nearest distance.
                        bestPos  = p;
                        bestDist = d;
                        bestRef  = cur;
                    }
                }
                else
                {
                    // Skip already visited.
                    if (closed.Contains(conn))
                    {
                        continue;
                    }
                    // Store to closed with parent for trace back.
                    closed.Add(conn);
#if ASTARDEBUG
                    Debug.DrawLine((Vector3)cur.position, (Vector3)conn.position, Color.black);
                    Debug.DrawLine((Vector3)graph.vertices[sp] + Vector3.up * 0.1F, (Vector3)graph.vertices[sq] + Vector3.up * 0.1F, Color.blue);
#endif

                    // Non-blocked edge, follow if within search radius.
                    p = Mathfx.NearestPointStrictXZ((Vector3)graph.vertices[sp], (Vector3)graph.vertices[sq], searchPos);

                    d = Mathfx.MagnitudeXZ(p, searchPos);
                    if (d <= searchRadius)
                    {
#if ASTARDEBUG
                        Debug.DrawLine((Vector3)searchPos - Vector3.up * 0.1F, p - Vector3.up * 0.1F, Color.cyan);
#endif
                        stack.Push(conn);
                    }
#if ASTARDEBUG
                    else
                    {
                        Debug.DrawLine((Vector3)searchPos - Vector3.up * 0.1F, p - Vector3.up * 0.1F, Color.red);
                    }
#endif
                }
            }
        }
        // Trace back and store visited curgons.

        /* followVisited(bestRef,visited,closed);
         * // Store best movement position.*/
        clampedPos = bestPos;
        // Return number of visited curs.
        return(bestRef);       //visited.size();
    }
Beispiel #25
0
    override public void Update()
    {
        //if (m_Human.PlayerProperty != null)

        //Debug.Log(Time.timeSinceLevelLoad + " " + this.ToString() + " - update " + State.ToString() + " " + EndOfStateTime);

        if (State == E_State.Death)
        {
            return;
        }

        if (RotationOk == false)
        {
            CurrentRotationTime += Time.deltaTime;

            if (CurrentRotationTime >= RotationTime)
            {
                CurrentRotationTime = RotationTime;
                RotationOk          = true;
            }

            float      progress = CurrentRotationTime / RotationTime;
            Quaternion q        = Quaternion.Lerp(StartRotation, FinalRotation, progress);
            Owner.Transform.rotation = q;
        }

        if (PositionOK == false)
        {
            CurrentMoveTime += Time.deltaTime;
            if (CurrentMoveTime >= MoveTime)
            {
                CurrentMoveTime = MoveTime;
                PositionOK      = true;
            }

            float   progress = CurrentMoveTime / MoveTime;
            Vector3 finalPos = Mathfx.Sinerp(StartPosition, FinalPosition, progress);
            //MoveTo(finalPos);
            if (Move(finalPos - Transform.position) == false)
            {
                PositionOK = true;
            }
        }

        switch (State)
        {
        case E_State.Start:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                InitializeKnockdownLoop();
            }
            break;

        case E_State.Loop:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                InitializeKnockdownUp();
            }
            break;

        case E_State.Fatality:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                if (ActionDeath != null)
                {
                    ActionDeath.SetSuccess();
                    ActionDeath = null;
                }
                InitializeDeath();
            }
            break;

        case E_State.End:
            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                Release();
            }
            break;

        case E_State.Death:
            break;
        }
    }
Beispiel #26
0
        private void SetFlightCtrlState(Vector3d act, Vector3d deltaEuler, FlightCtrlState s, float drive_limit)
        {
            bool userCommandingPitchYaw = (Mathfx.Approx(s.pitch, s.pitchTrim, 0.1F) ? false : true) || (Mathfx.Approx(s.yaw, s.yawTrim, 0.1F) ? false : true);
            bool userCommandingRoll     = (Mathfx.Approx(s.roll, s.rollTrim, 0.1F) ? false : true);

            // Disable the new SAS so it won't interfere.
            // Todo : enable it when it's a good idea or the user had it enabled before
            part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false);

            if (attitudeKILLROT)
            {
                if (lastReferencePart != vessel.GetReferenceTransformPart() || userCommandingPitchYaw || userCommandingRoll)
                {
                    attitudeTo(Quaternion.LookRotation(vessel.GetTransform().up, -vessel.GetTransform().forward), AttitudeReference.INERTIAL, null);
                    lastReferencePart = vessel.GetReferenceTransformPart();
                }
            }
            if (userCommandingPitchYaw || userCommandingRoll)
            {
                pid.Reset();
            }

            if (!attitudeRollMatters)
            {
                attitudeTo(Quaternion.LookRotation(attitudeTarget * Vector3d.forward, attitudeWorldToReference(-vessel.GetTransform().forward, attitudeReference)), attitudeReference, null);
                _attitudeRollMatters = false;
            }

            if (!userCommandingRoll)
            {
                if (!double.IsNaN(act.z))
                {
                    s.roll = Mathf.Clamp((float)(act.z), -drive_limit, drive_limit);
                }
            }

            if (!userCommandingPitchYaw)
            {
                if (!double.IsNaN(act.x))
                {
                    s.pitch = Mathf.Clamp((float)(act.x), -drive_limit, drive_limit);
                }
                if (!double.IsNaN(act.y))
                {
                    s.yaw = Mathf.Clamp((float)(act.y), -drive_limit, drive_limit);
                }
            }

            // RCS and SAS control:
            Vector3d absErr;            // Absolute error (exag º)

            absErr.x = Math.Abs(deltaEuler.x);
            absErr.y = Math.Abs(deltaEuler.y);
            absErr.z = Math.Abs(deltaEuler.z);

            if ((absErr.x < 0.4) && (absErr.y < 0.4) && (absErr.z < 0.4))
            {
                if (timeCount < 50)
                {
                    timeCount++;
                }
                else
                {
                    if (RCS_auto)
                    {
                        if (attitudeRCScontrol && core.rcs.users.Count == 0)
                        {
                            part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false);
                        }
                    }
                }
            }
            else if ((absErr.x > 1.0) || (absErr.y > 1.0) || (absErr.z > 1.0))
            {
                timeCount = 0;
                if (RCS_auto && ((absErr.x > 3.0) || (absErr.y > 3.0) || (absErr.z > 3.0)))
                {
                    if (attitudeRCScontrol)
                    {
                        part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true);
                    }
                }
            }
        } // end of SetFlightCtrlState
Beispiel #27
0
 public override void Update()
 {
     if (State == E_State.E_Preparing)
     {
         bool dontMove = false;
         if (RotationOk == false)
         {
             CurrentRotationTime += Time.deltaTime;
             if (CurrentRotationTime >= RotationTime)
             {
                 CurrentRotationTime = RotationTime;
                 RotationOk          = true;
             }
             else
             {
                 float      progress = CurrentRotationTime / RotationTime;
                 Quaternion q        = Quaternion.Lerp(StartRotation, FinalRotation, progress);
                 Owner.Transform.rotation = q;
                 if (Quaternion.Angle(q, FinalRotation) > 20.0f)
                 {
                     dontMove = true;
                 }
             }
         }
         if (dontMove == true && PositionOk == false)
         {
             CurrentMoveTime += Time.deltaTime;
             if (CurrentMoveTime >= MoveTime)
             {
                 CurrentMoveTime = MoveTime;
                 PositionOk      = true;
             }
             if (CurrentMoveTime > 0)
             {
                 float   progress = CurrentMoveTime / MoveTime;
                 Vector3 finalPos = Mathfx.Hermite(StartPosition, FinalPosition, progress);//todo
                 if (Move(finalPos - Transform.position) == false)
                 {
                     PositionOk = true;
                 }
             }
         }
         if (PositionOk && RotationOk)
         {
             State = E_State.E_Attacking;
             Debug.Log("Attacking Start");
             PlayAnim();
         }
     }
     else if (State == E_State.E_Attacking)
     {
         CurrentMoveTime += Time.deltaTime;
         if (AttackPhaseTime < Time.timeSinceLevelLoad)
         {
             State = E_State.E_Finished;
         }
         Debug.Log("CurrentMoveTime=" + CurrentMoveTime);
         Debug.Log("MoveTime=" + MoveTime);
         if (CurrentMoveTime >= MoveTime)
         {
             CurrentMoveTime = MoveTime;
         }
         if (CurrentMoveTime > 0 && CurrentMoveTime <= MoveTime)
         {
             float   progress = CurrentMoveTime / MoveTime;
             Vector3 finalPos = Mathfx.Hermite(StartPosition, FinalPosition, progress);//todo
             if (Move(finalPos - Transform.position) == false)
             {
                 CurrentMoveTime = MoveTime;
             }
         }
         if (Action.IsHit == false && HitTime <= Time.timeSinceLevelLoad)
         {
             Action.IsHit = true;
         }
     }
     else if (State == E_State.E_Finished)
     {
         Debug.Log("Attack Is Finished");
         Action.AttackPhaseDone = true;
         Release();
     }
     //base.Update();
 }
Beispiel #28
0
    void RotateToTarget()
    {
        if (EndOfStateTime == 0)
        {
            StartRotation = Owner.Transform.rotation;

            Vector3 finalDir;
            if (Owner.BlackBoard.desiredTarget != null)
            {
                finalDir = (Owner.BlackBoard.desiredTarget.Position + (Owner.BlackBoard.desiredTarget.GetComponent <BlackBoard>().moveDir *Owner.BlackBoard.desiredTarget.GetComponent <BlackBoard>().speed * 0.5f)) - Owner.Transform.position;
                finalDir.Normalize();
            }
            else
            {
                finalDir = Owner.Transform.forward;
            }

            FinalRotation.SetLookRotation(finalDir);
            float rotateAngle = Vector3.Angle(Owner.Transform.forward, finalDir);
            if (rotateAngle < 30)
            {
                return;
            }
            RotationTime = rotateAngle / (360.0f * Owner.BlackBoard.rotationSmooth);
            //if (RotationTime == 0)
            //{
            //  return;
            //}

            if (Vector3.Dot(finalDir, Owner.Transform.right) > 0)
            {
                AnimName = Owner.AnimSet.GetRotateAnim(Owner.BlackBoard.motionType, RotationType.RIGHT);
            }
            else
            {
                AnimName = Owner.AnimSet.GetRotateAnim(Owner.BlackBoard.motionType, RotationType.LEFT);
            }
            CrossFade(AnimName, 0.01f);

            float animLen = Owner.AnimEngine[AnimName].length;
            int   steps   = Mathf.CeilToInt(RotationTime / animLen);
            EndOfStateTime = Owner.AnimEngine[AnimName].length * steps + Time.timeSinceLevelLoad;
        }
        else
        {
            CurrentRotationTime += Time.deltaTime * 0.5f;
            if (CurrentRotationTime >= RotationTime)
            {
                CurrentRotationTime = RotationTime;
            }

            float      progress = CurrentRotationTime / RotationTime;
            Quaternion q        = Quaternion.Lerp(StartRotation, FinalRotation, Mathfx.Hermite(0, 1, progress));
            Owner.Transform.rotation = q;

            if (EndOfStateTime <= Time.timeSinceLevelLoad)
            {
                EndOfStateTime = 0;
                CrossFade(Owner.AnimSet.GetIdleAnim(Owner.BlackBoard.weaponSelected, Owner.BlackBoard.weaponState), 0.2f); // 播放待机动作
            }
        }
    }
Beispiel #29
0
        private void SetFlightCtrlState(Vector3d act, Vector3d deltaEuler, FlightCtrlState s, float drive_limit)
        {
            bool userCommandingPitchYaw = (Mathfx.Approx(s.pitch, s.pitchTrim, 0.1F) ? false : true) || (Mathfx.Approx(s.yaw, s.yawTrim, 0.1F) ? false : true);
            bool userCommandingRoll     = (Mathfx.Approx(s.roll, s.rollTrim, 0.1F) ? false : true);

            // Disable the new SAS so it won't interfere. But enable it while in timewarp for compatibility with PersistentRotation
            if (TimeWarp.WarpMode != TimeWarp.Modes.HIGH || TimeWarp.CurrentRateIndex == 0)
            {
                part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false);
            }


            if (attitudeKILLROT)
            {
                if (lastReferencePart != vessel.GetReferenceTransformPart() || userCommandingPitchYaw || userCommandingRoll)
                {
                    attitudeTo(Quaternion.LookRotation(vessel.GetTransform().up, -vessel.GetTransform().forward), AttitudeReference.INERTIAL, null);
                    lastReferencePart = vessel.GetReferenceTransformPart();
                }
            }
            if (userCommandingPitchYaw || userCommandingRoll)
            {
                pid.Reset();
            }

            if (!userCommandingRoll)
            {
                if (!double.IsNaN(act.z))
                {
                    s.roll = Mathf.Clamp((float)(act.z), -drive_limit, drive_limit);
                }
            }

            if (!userCommandingPitchYaw)
            {
                if (!double.IsNaN(act.x))
                {
                    s.pitch = Mathf.Clamp((float)(act.x), -drive_limit, drive_limit);
                }
                if (!double.IsNaN(act.y))
                {
                    s.yaw = Mathf.Clamp((float)(act.y), -drive_limit, drive_limit);
                }
            }

            // RCS and SAS control:
            Vector3d absErr;            // Absolute error (exag º)

            absErr.x = Math.Abs(deltaEuler.x);
            absErr.y = Math.Abs(deltaEuler.y);
            absErr.z = Math.Abs(deltaEuler.z);

            if ((absErr.x < 0.4) && (absErr.y < 0.4) && (absErr.z < 0.4))
            {
                if (timeCount < 50)
                {
                    timeCount++;
                }
                else
                {
                    if (RCS_auto)
                    {
                        if (attitudeRCScontrol && core.rcs.users.Count == 0)
                        {
                            part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false);
                        }
                    }
                }
            }
            else if ((absErr.x > 1.0) || (absErr.y > 1.0) || (absErr.z > 1.0))
            {
                timeCount = 0;
                if (RCS_auto && ((absErr.x > 3.0) || (absErr.y > 3.0) || (absErr.z > 3.0)))
                {
                    if (attitudeRCScontrol)
                    {
                        part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true);
                    }
                }
            }
        } // end of SetFlightCtrlState
Beispiel #30
0
    public override void OnUpdate()
    {
        if (_attackStatus == AttackStatus.PREPARING)
        {
            bool dontMove = false;
            if (_rotationOk == false)
            {
                _currentRotationTime += Time.deltaTime;
                if (_currentRotationTime >= _rotationTime)
                {
                    _currentRotationTime = _rotationTime;
                    _rotationOk          = true;
                }
                float      progress = _currentRotationTime / _rotationTime;
                Quaternion rotation = Quaternion.Lerp(_startRotation, _finalRotation, progress);
                Agent.Transform.rotation = rotation;
            }

            if (_positionOK == false)
            {
                _currentMoveTime += Time.deltaTime;
                if (_currentMoveTime >= _moveTime)
                {
                    _currentMoveTime = _moveTime;
                    _positionOK      = true;
                }

                if (_currentMoveTime > 0)
                {
                    float   progress = _currentMoveTime / _moveTime;
                    Vector3 finalPos = Mathfx.Hermite(_startPosition, _finalPosition, progress);
                    //if (MoveToCollideWithEnemy(finalPos, Transform.forward) == false)
                    if (TransformTools.MoveOnGround(Agent.transform, Agent.CharacterController,
                                                    finalPos - Agent.Transform.position, true) == false)
                    {
                        _positionOK = true;
                    }
                }
            }

            if (_rotationOk && _positionOK)
            {
                _attackStatus = AttackStatus.ATTACKING;
                InitializeAttacking();
            }
        }
        else if (_attackStatus == AttackStatus.ATTACKING)
        {
            _currentMoveTime += Time.deltaTime;
            if (_currentMoveTime >= _moveTime)
            {
                _currentMoveTime = _moveTime;
            }

            if (_currentMoveTime > 0 && _currentMoveTime <= _moveTime)
            {
                float   progress = Mathf.Min(1.0f, _currentMoveTime / _moveTime);
                Vector3 finalPos = Mathfx.Hermite(_startPosition, _finalPosition, progress);
                //if (MoveToCollideWithEnemy(finalPos, Transform.forward) == false)
                if (TransformTools.MoveOnGround(Agent.transform, Agent.CharacterController,
                                                finalPos - Agent.Transform.position, false) == false)
                {
                    _currentMoveTime = _moveTime;
                }
            }

            if (_hitTimeStart == false && _hitTime <= Time.timeSinceLevelLoad)
            {
                _hitTimeStart = true;
                HandleAttackResult.DoMeleeDamage(Agent, _eventAttackCross.target, Agent.BlackBoard.attackerWeapon,
                                                 _eventAttackCross.animAttackData, _isCritical, _knockdown,
                                                 _eventAttackCross.animAttackData.isFatal);
            }

            if (_attackPhaseTime < Time.timeSinceLevelLoad)
            {
                if (--_remainAttackCount > 0)
                {
                    // 再次攻击
                    InitializeAttacking(false);
                }
                else
                {
                    _attackStatus = AttackStatus.FINISHED;
                }
            }
        }
        else if (_attackStatus == AttackStatus.FINISHED && _endOfStateTime <= Time.timeSinceLevelLoad)
        {
            //Debug.Log(Time.timeSinceLevelLoad + " attack finished");
            IsFinished = true;
            _eventAttackCross.IsFinished = true;
        }
    }