Esempio n. 1
0
        void FixedUpdate()
        {
            if (!gameObject.activeInHierarchy)
            {
                return;
            }

            //gravity
            velocity += FlightGlobals.getGeeForceAtPosition(transform.position) * TimeWarp.fixedDeltaTime
                        + Krakensbane.GetLastCorrection();

            //drag
            velocity -= 0.005f * (velocity + Krakensbane.GetFrameVelocityV3f()) * atmDensity;

            transform.rotation *= Quaternion.Euler(angularVelocity * TimeWarp.fixedDeltaTime);
            transform.position += velocity * TimeWarp.deltaTime;

            if (BDArmorySettings.SHELL_COLLISIONS)
            {
                RaycastHit hit;
                if (Physics.Linecast(transform.position, transform.position + velocity * Time.fixedDeltaTime, out hit,
                                     557057))
                {
                    velocity  = Vector3.Reflect(velocity, hit.normal);
                    velocity *= 0.55f;
                    velocity  = Quaternion.AngleAxis(Random.Range(0f, 90f), Random.onUnitSphere) *
                                velocity;
                }
            }
        }
Esempio n. 2
0
        void DropFlare()
        {
            PartResource cmResource = GetCMResource();

            if (cmResource == null || !(cmResource.amount >= 1))
            {
                return;
            }
            cmResource.amount--;
            audioSource.pitch = UnityEngine.Random.Range(0.9f, 1.1f);
            audioSource.PlayOneShot(cmSound);

            GameObject cm = flarePool.GetPooledObject();

            cm.transform.position = transform.position;
            CMFlare cmf = cm.GetComponent <CMFlare>();

            cmf.velocity = part.rb.velocity
                           + Krakensbane.GetFrameVelocityV3f()
                           + (ejectVelocity * transform.up)
                           + (UnityEngine.Random.Range(-3f, 3f) * transform.forward)
                           + (UnityEngine.Random.Range(-3f, 3f) * transform.right);
            cmf.SetThermal(vessel);

            cm.SetActive(true);

            FireParticleEffects();
        }
Esempio n. 3
0
        public Vector3 GetVelocity(Rigidbody rigidbody, Vector3 refPoint) // from Ferram
        {
            Vector3 newVelocity = Vector3.zero;

            newVelocity += rigidbody.GetPointVelocity(refPoint);
            newVelocity += Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime;
            return(newVelocity);
        }
Esempio n. 4
0
        /*public void ClearShielding()
        {
            isShielded = false;
        }

        public void ActivateShielding()
        {
            isShielded = true;
            Cl = 0;
            Cd = 0;
            Cm = 0;
        }*/
        public virtual Vector3d GetVelocity()
        {
            if (HighLogic.LoadedSceneIsFlight)
                return part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f()
                    - FARWind.GetWind(FlightGlobals.currentMainBody, part, part.Rigidbody.position);
            else
                return velocityEditor;
        }
Esempio n. 5
0
    public Vector3 GetVelocity(Rigidbody rigidbody, Vector3 refPoint) // from Ferram
    {
        Vector3 newVelocity = Vector3.zero;

        //newVelocity = commonRigidBody.velocity + Krakensbane.GetFrameVelocity() + Vector3.Cross(commonRigidBody.angularVelocity, liftTransform.position - commonRigidBody.position);
        newVelocity += rigidbody.GetPointVelocity(refPoint);
        newVelocity += Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime;
        return(newVelocity);
    }
Esempio n. 6
0
 public Vector3d GetVelocity()
 {
     if (HighLogic.LoadedSceneIsFlight)
     {
         return(part.Rigidbody.velocity +
                Krakensbane.GetFrameVelocityV3f() -
                FARWind.GetWind(FlightGlobals.currentMainBody, part, part.Rigidbody.position));
     }
     return(velocityEditor);
 }
Esempio n. 7
0
        private void CalculateAndApplyVesselAeroProperties()
        {
            float atmDensity = (float)_vessel.atmDensity;

            if (atmDensity <= 0)
            {
                machNumber     = 0;
                reynoldsNumber = 0;
                return;
            }

            machNumber     = _vessel.mach;
            reynoldsNumber = FARAeroUtil.CalculateReynoldsNumber(_vessel.atmDensity, Length, _vessel.srfSpeed, machNumber, FlightGlobals.getExternalTemperature((float)_vessel.altitude, _vessel.mainBody), _vessel.mainBody.atmosphereAdiabaticIndex);
            float skinFrictionDragCoefficient = (float)FARAeroUtil.SkinFrictionDrag(reynoldsNumber, machNumber);

            Vector3 frameVel = Krakensbane.GetFrameVelocityV3f();

            if (_updateQueued)                                           //only happens if we have an voxelization scheduled, then we need to check for null
            {
                for (int i = _currentAeroModules.Count - 1; i >= 0; i--) //start from the top and come down to improve performance if it needs to remove anything
                {
                    FARAeroPartModule m = _currentAeroModules[i];
                    if (m != null)
                    {
                        m.UpdateVelocityAndAngVelocity(frameVel);
                    }
                    else
                    {
                        _currentAeroModules.RemoveAt(i);
                        i++;
                    }
                }
            }
            else                                                         //otherwise, we don't need to do Unity's expensive "is this part dead" null-check
            {
                for (int i = _currentAeroModules.Count - 1; i >= 0; i--) //start from the top and come down to improve performance if it needs to remove anything
                {
                    FARAeroPartModule m = _currentAeroModules[i];
                    m.UpdateVelocityAndAngVelocity(frameVel);
                }
            }

            for (int i = 0; i < _currentAeroSections.Count; i++)
            {
                _currentAeroSections[i].FlightCalculateAeroForces(atmDensity, (float)machNumber, (float)(reynoldsNumber / Length), skinFrictionDragCoefficient);
            }

            _vesselIntakeRamDrag.ApplyIntakeRamDrag((float)machNumber, _vessel.srf_velocity.normalized, (float)_vessel.dynamicPressurekPa);

            for (int i = 0; i < _currentAeroModules.Count; i++)
            {
                FARAeroPartModule m = _currentAeroModules[i];
                m.ApplyForces();
            }
        }
        private void CalculateAndApplyVesselAeroProperties()
        {
            float atmDensity = (float)vessel.atmDensity;

            if (atmDensity <= 0)
            {
                MachNumber     = 0;
                ReynoldsNumber = 0;
                return;
            }

            MachNumber     = vessel.mach;
            ReynoldsNumber = FARAeroUtil.CalculateReynoldsNumber(vessel.atmDensity,
                                                                 Length,
                                                                 vessel.srfSpeed,
                                                                 MachNumber,
                                                                 FlightGlobals.getExternalTemperature((float)vessel
                                                                                                      .altitude,
                                                                                                      vessel.mainBody),
                                                                 vessel.mainBody.atmosphereAdiabaticIndex);
            float skinFrictionDragCoefficient = (float)FARAeroUtil.SkinFrictionDrag(ReynoldsNumber, MachNumber);

            float pseudoKnudsenNumber = (float)(MachNumber / (ReynoldsNumber + MachNumber));

            Vector3 frameVel = Krakensbane.GetFrameVelocityV3f();

            //start from the top and come down to improve performance if it needs to remove anything
            for (int i = _currentAeroModules.Count - 1; i >= 0; i--)
            {
                FARAeroPartModule m = _currentAeroModules[i];
                if (m != null && m.part != null && m.part.partTransform != null)
                {
                    m.UpdateVelocityAndAngVelocity(frameVel);
                }
                else
                {
                    _currentAeroModules.RemoveAt(i);
                }
            }

            foreach (FARAeroSection aeroSection in _currentAeroSections)
            {
                aeroSection.FlightCalculateAeroForces((float)MachNumber,
                                                      (float)(ReynoldsNumber / Length),
                                                      pseudoKnudsenNumber,
                                                      skinFrictionDragCoefficient);
            }

            _vesselIntakeRamDrag.ApplyIntakeRamDrag((float)MachNumber, vessel.srf_velocity.normalized);

            foreach (FARAeroPartModule m in _currentAeroModules)
            {
                m.ApplyForces();
            }
        }
 public virtual Vector3d GetVelocity()
 {
     if (start != StartState.Editor)
     {
         return(part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f());
     }
     else
     {
         return(velocityEditor);
     }
 }
 public virtual Vector3d GetVelocity()
 {
     if (HighLogic.LoadedSceneIsFlight)
     {
         return(part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f());
     }
     else
     {
         return(velocityEditor);
     }
 }
Esempio n. 11
0
 void OnGUI()
 {
     if (BDArmorySettings.DRAW_DEBUG_LABELS)
     {
         var frameVelocity = Krakensbane.GetFrameVelocityV3f();
         GUI.Label(new Rect(10, 60, 400, 400),
                   $"Frame velocity: {frameVelocity.magnitude} ({frameVelocity}){Environment.NewLine}"
                   + $"Last offset {Time.time - lastShift}s ago{Environment.NewLine}"
                   + $"Local vessel speed: {FlightGlobals.ActiveVessel.rb_velocity.magnitude}, ({FlightGlobals.ActiveVessel.rb_velocity}){Environment.NewLine}"
                   //+ $"Ref frame is {(FlightGlobals.RefFrameIsRotating ? "" : "not ")}rotating{Environment.NewLine}"
                   );
     }
 }
Esempio n. 12
0
        public Vector3 GetVelocity(Rigidbody rigidbody, Vector3 refPoint) // from Ferram
        {
            Vector3 newVelocity = Vector3.zero;

            try
            {
                newVelocity += rigidbody.GetPointVelocity(refPoint);
                newVelocity += Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime;
            }
            catch (Exception e)
            {
                Log.err("FSengineBladed GetVelocity Exception!");
                Log.ex(this, e);
            }
            return(newVelocity);
        }
Esempio n. 13
0
        private void UpdateWaterContact(double depth)
        {
            if (depth < 0)      //corresponds to above the ocean
            {
                if (part.WaterContact)
                {
                    part.WaterContact = false;
                    vessel.checkSplashed();
                }
                if (depthFactor < -1)
                {
                    splashDrag          = 0;
                    part.rb.drag        = 0;
                    part.rb.angularDrag = 0;
                }
                return;
            }

            float tmp = 0.15f;      //base drag

            tmp /= part.Rigidbody.mass;
            if (splashDrag > tmp)
            {
                splashDrag = splashDrag * 0.98f;
            }
            else
            {
                splashDrag = tmp;
            }

            if (!part.WaterContact)
            {
                part.WaterContact = true;
                vessel.checkSplashed();

                float vertVec = Vector3.Dot(part.rb.velocity + Krakensbane.GetFrameVelocityV3f(), vessel.upAxis);
                vertVec *= 0.1f;
                if (vertVec > 1)
                {
                    vertVec = 1;
                }

                splashDrag = Math.Max(20f * vertVec / part.rb.mass, tmp);
            }
            part.rb.drag        = splashDrag;
            part.rb.angularDrag = splashDrag * 10;
        }
Esempio n. 14
0
        private void CalculateAndApplyVesselAeroProperties()
        {
            float atmDensity = (float)_vessel.atmDensity;

            if (atmDensity <= 0)
            {
                machNumber     = 0;
                reynoldsNumber = 0;
                return;
            }

            machNumber     = _vessel.mach;
            reynoldsNumber = FARAeroUtil.CalculateReynoldsNumber(_vessel.atmDensity, Length, _vessel.srfSpeed, machNumber, FlightGlobals.getExternalTemperature((float)_vessel.altitude, _vessel.mainBody), _vessel.mainBody.atmosphereAdiabaticIndex);
            float skinFrictionDragCoefficient = (float)FARAeroUtil.SkinFrictionDrag(reynoldsNumber, machNumber);

            Vector3 frameVel = Krakensbane.GetFrameVelocityV3f();

            for (int i = 0; i < _currentAeroModules.Count; i++)
            {
                FARAeroPartModule m = _currentAeroModules[i];
                if (m != null)
                {
                    m.UpdateVelocityAndAngVelocity(frameVel);
                }
                else
                {
                    _currentAeroModules.RemoveAt(i);
                    i--;
                }
            }

            for (int i = 0; i < _currentAeroSections.Count; i++)
            {
                _currentAeroSections[i].FlightCalculateAeroForces(atmDensity, (float)machNumber, (float)(reynoldsNumber / Length), skinFrictionDragCoefficient);
            }

            _vesselIntakeRamDrag.ApplyIntakeRamDrag((float)machNumber, _vessel.srf_velocity.normalized, (float)_vessel.dynamicPressurekPa);

            for (int i = 0; i < _currentAeroModules.Count; i++)
            {
                FARAeroPartModule m = _currentAeroModules[i];
                if ((object)m != null)
                {
                    m.ApplyForces();
                }
            }
        }
 void UpdateAerodynamics(ModularFI.ModularFlightIntegrator fi, Part part)
 {
     if (part.dragModel != Part.DragModel.CYLINDRICAL)// || part.Modules.Contains("KerbalEVA"))     //FIXME Proper model for airbrakes
     {
         fi.BaseFIUpdateAerodynamics(part);
         return;
     }
     else if (!part.DragCubes.None)
     {
         Rigidbody rb = part.Rigidbody;
         if (rb)
         {
             part.dragVectorDir      = -rb.velocity - Krakensbane.GetFrameVelocityV3f().normalized;
             part.dragVectorDirLocal = part.partTransform.worldToLocalMatrix.MultiplyVector(part.dragVectorDir);
             part.DragCubes.SetDrag(part.dragVectorDirLocal, (float)part.machNumber);
         }
     }
 }
Esempio n. 16
0
 void OnGUI()
 {
     if (BDArmorySettings.DRAW_DEBUG_LABELS)
     {
         var frameVelocity = Krakensbane.GetFrameVelocityV3f();
         //var rFrameVelocity = FlightGlobals.currentMainBody.getRFrmVel(Vector3d.zero);
         //var rFrameRotation = rFrameVelocity - FlightGlobals.currentMainBody.getRFrmVel(VectorUtils.GetUpDirection(Vector3.zero));
         GUI.Label(new Rect(10, 60, 400, 400),
                   $"Frame velocity: {frameVelocity.magnitude} ({frameVelocity}){Environment.NewLine}"
                   + $"Last offset {Time.time - lastShift}s ago{Environment.NewLine}"
                   + $"Local vessel speed: {FlightGlobals.ActiveVessel.rb_velocity.magnitude}, ({FlightGlobals.ActiveVessel.rb_velocity}){Environment.NewLine}"
                   //+ $"Reference frame speed: {rFrameVelocity}{Environment.NewLine}"
                   //+ $"Reference frame rotation speed: {rFrameRotation}{Environment.NewLine}"
                   //+ $"Reference frame angular speed: {rFrameRotation.magnitude / Mathf.PI * 180}{Environment.NewLine}"
                   //+ $"Ref frame is {(FlightGlobals.RefFrameIsRotating ? "" : "not ")}rotating{Environment.NewLine}"
                   );
     }
 }
Esempio n. 17
0
        public Vector3 GetVelocity(Rigidbody rigidbody, Vector3 refPoint) // from Ferram
        {
            Vector3 newVelocity = Vector3.zero;

            try
            {
                newVelocity += rigidbody.GetPointVelocity(refPoint);
                newVelocity += Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime;
            }
            catch (Exception e)
            {
                if (debugMode)
                {
                    Debug.Log("FSengineBladed GetVelocity Exception " + e.GetType().ToString());
                }
            }
            return(newVelocity);
        }
Esempio n. 18
0
        private bool CheckDieOnHighVelocity(Rigidbody body)
        {
            Vector3d velVector = body.velocity + Krakensbane.GetFrameVelocityV3f();

            double vertVec = Vector3d.Dot(velVector, vessel.upAxis);

            if (Math.Abs(vertVec) > part.crashTolerance * vertCrashTolFactor)
            {
                GameEvents.onCrashSplashdown.Fire(new EventReport(FlightEvents.SPLASHDOWN_CRASH, part, part.partInfo.title, "", 0, ""));
                part.Die();
                return(true);
            }
            double horizVel = (velVector - vertVec * vessel.upAxis).magnitude;

            if (horizVel > part.crashTolerance * horizCrashTolFactor)
            {
                GameEvents.onCrashSplashdown.Fire(new EventReport(FlightEvents.SPLASHDOWN_CRASH, part, part.partInfo.title, "", 0, ""));
                part.Die();
                return(true);
            }
            return(false);
        }
Esempio n. 19
0
        void FixedUpdate()
        {
            //floating origin and velocity offloading corrections
            if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero())
            {
                transform.position -= FloatingOrigin.OffsetNonKrakensbane;
                prevPosition       -= FloatingOrigin.OffsetNonKrakensbane;
            }

            if (Time.time - startTime < stayTime && transform.parent != null)
            {
                transform.rotation = transform.parent.rotation;
                transform.position = spawnTransform.position;
                //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime);
            }
            else
            {
                if (transform.parent != null && parentRB)
                {
                    transform.parent = null;
                    rb.isKinematic   = false;
                    rb.velocity      = parentRB.velocity + Krakensbane.GetFrameVelocityV3f();
                }
            }

            if (rb && !rb.isKinematic)
            {
                //physics
                if (FlightGlobals.RefFrameIsRotating)
                {
                    rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position) * Time.fixedDeltaTime;
                }

                //guidance and attitude stabilisation scales to atmospheric density.
                float atmosMultiplier =
                    Mathf.Clamp01(2.5f *
                                  (float)
                                  FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position),
                                                              FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody));

                //model transform. always points prograde
                transform.rotation = Quaternion.RotateTowards(transform.rotation,
                                                              Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up),
                                                              atmosMultiplier * (0.5f * (Time.time - startTime)) * 50 * Time.fixedDeltaTime);

                if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime)
                {
                    float random  = randomThrustDeviation * (1 - (Mathf.PerlinNoise(4 * Time.time, randThrustSeed) * 2));
                    float random2 = randomThrustDeviation * (1 - (Mathf.PerlinNoise(randThrustSeed, 4 * Time.time) * 2));
                    rb.AddRelativeForce(new Vector3(random, random2, thrust));
                }
            }

            if (Time.time - startTime > thrustTime)
            {
                //isThrusting = false;
                IEnumerator <KSPParticleEmitter> pEmitter = pEmitters.AsEnumerable().GetEnumerator();
                while (pEmitter.MoveNext())
                {
                    if (pEmitter.Current == null)
                    {
                        continue;
                    }
                    if (pEmitter.Current.useWorldSpace)
                    {
                        pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0.1f, 0.05f);
                        pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0.2f, 0.05f);
                    }
                    else
                    {
                        pEmitter.Current.minSize = Mathf.MoveTowards(pEmitter.Current.minSize, 0, 0.1f);
                        pEmitter.Current.maxSize = Mathf.MoveTowards(pEmitter.Current.maxSize, 0, 0.1f);
                        if (pEmitter.Current.maxSize == 0)
                        {
                            pEmitter.Current.emit = false;
                        }
                    }
                }
                pEmitter.Dispose();
            }

            if (Time.time - startTime > 0.1f + stayTime)
            {
                currPosition = transform.position;
                float      dist = (currPosition - prevPosition).magnitude;
                Ray        ray  = new Ray(prevPosition, currPosition - prevPosition);
                RaycastHit hit;
                KerbalEVA  hitEVA = null;
                //if (Physics.Raycast(ray, out hit, dist, 2228224))
                //{
                //    try
                //    {
                //        hitEVA = hit.collider.gameObject.GetComponentUpwards<KerbalEVA>();
                //        if (hitEVA != null)
                //            Debug.Log("[BDArmory]:Hit on kerbal confirmed!");
                //    }
                //    catch (NullReferenceException)
                //    {
                //        Debug.Log("[BDArmory]:Whoops ran amok of the exception handler");
                //    }

                //    if (hitEVA && hitEVA.part.vessel != sourceVessel)
                //    {
                //        Detonate(hit.point);
                //    }
                //}

                if (!hitEVA)
                {
                    if (Physics.Raycast(ray, out hit, dist, 9076737))
                    {
                        Part hitPart = null;
                        try
                        {
                            KerbalEVA eva = hit.collider.gameObject.GetComponentUpwards <KerbalEVA>();
                            hitPart = eva ? eva.part : hit.collider.gameObject.GetComponentInParent <Part>();
                        }
                        catch (NullReferenceException)
                        {
                        }

                        if (hitPart == null || (hitPart != null && hitPart.vessel != sourceVessel))
                        {
                            Detonate(hit.point);
                        }
                    }
                    else if (FlightGlobals.getAltitudeAtPos(transform.position) < 0)
                    {
                        Detonate(transform.position);
                    }
                }
            }
            else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0)
            {
                Detonate(currPosition);
            }
            prevPosition = currPosition;

            if (Time.time - startTime > lifeTime)
            {
                Detonate(transform.position);
            }
        }
Esempio n. 20
0
        private void FixedUpdate()
        {
            //Flight values
            if (!CompatibilityChecker.IsAllCompatible() || !HighLogic.LoadedSceneIsFlight || FlightGlobals.ActiveVessel == null || this.part.Rigidbody == null || ((IntPtr.Size == 8) && (Environment.OSVersion.Platform == PlatformID.Win32NT)))
            {
                return;
            }
            pos         = this.part.transform.position;
            ASL         = FlightGlobals.getAltitudeAtPos(pos);
            trueAlt     = this.vessel.GetTrueAlt(ASL);
            atmPressure = this.vessel.mainBody.GetPressureAtAlt(ASL);
            atmDensity  = this.vessel.mainBody.GetDensityAtAlt(ASL);
            Vector3 velocity = this.part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f();

            sqrSpeed   = velocity.sqrMagnitude;
            dragVector = -velocity.normalized;
            if (!this.staged && GameSettings.LAUNCH_STAGES.GetKeyDown() && this.vessel.isActiveVessel && this.part.inverseStage == Staging.CurrentStage)
            {
                ActivateRC();
            }
            if (this.deployOnGround && !this.staged)
            {
                if (!this.launched && !this.vessel.LandedOrSplashed)
                {
                    if (!this.vessel.LandedOrSplashed)
                    {
                        //Dampening timer
                        if (!this.launchTimer.isRunning)
                        {
                            this.launchTimer.Start();
                        }
                        if (this.launchTimer.elapsedMilliseconds >= 3000)
                        {
                            this.launchTimer.Reset();
                            this.launched = true;
                        }
                    }
                    else if (this.launchTimer.isRunning)
                    {
                        launchTimer.Reset();
                    }
                }
                if (this.launched && !groundStop && this.vessel.LandedOrSplashed)
                {
                    ActivateRC();
                }
            }

            if (this.staged)
            {
                //Checks if the parachute must disarm
                if (armed)
                {
                    this.part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                    if (parachutes.Any(p => p.canDeploy))
                    {
                        armed = false;
                    }
                }
                //Parachute deployments
                if (!armed)
                {
                    if (wait)
                    {
                        CheckForWait();
                        if (wait)
                        {
                            return;
                        }
                    }

                    //Parachutes
                    parachutes.ForEach(p => p.UpdateParachute());

                    //If all parachutes must be cut
                    if (allMustStop)
                    {
                        GUICut();
                        SetRepack();
                    }

                    //If the parachute can't be deployed
                    if (!oneWasDeployed && !settings.autoArm)
                    {
                        failedTimer.Start();
                        StagingReset();
                        Events["GUIDeploy"].active = true;
                        Events["GUIArm"].active    = true;
                    }
                }
            }
        }
Esempio n. 21
0
        void FixedUpdate()
        {
            if (!gameObject.activeInHierarchy)
            {
                return;
            }

            //floating origin and velocity offloading corrections
            if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero())
            {
                transform.position -= FloatingOrigin.OffsetNonKrakensbane;
                startPosition      -= FloatingOrigin.OffsetNonKrakensbane;
            }

            float distanceFromStart = Vector3.Distance(transform.position, startPosition);

            //calculate flight time for drag purposes
            flightTimeElapsed += Time.fixedDeltaTime;

            // calculate flight distance for achievement purposes
            distanceTraveled += currentVelocity.magnitude * Time.fixedDeltaTime;

            //Drag types currently only affect Impactvelocity
            //Numerical Integration is currently Broken
            switch (dragType)
            {
            case BulletDragTypes.None:
                break;

            case BulletDragTypes.AnalyticEstimate:
                CalculateDragAnalyticEstimate();
                break;

            case BulletDragTypes.NumericalIntegration:
                CalculateDragNumericalIntegration();
                break;
            }

            if (tracerLength == 0)
            {
                // visual tracer velocity is relative to the observer
                linePositions[0] = transform.position +
                                   ((currentVelocity - FlightGlobals.ActiveVessel.Velocity()) * tracerDeltaFactor * 0.45f * Time.fixedDeltaTime);
            }
            else
            {
                linePositions[0] = transform.position + ((currentVelocity - FlightGlobals.ActiveVessel.Velocity()).normalized * tracerLength);
            }

            if (fadeColor)
            {
                FadeColor();
                bulletTrail.material.SetColor("_TintColor", currentColor * tracerLuminance);
            }
            linePositions[1] = transform.position;

            bulletTrail.SetPositions(linePositions);
            currPosition = transform.position;

            if (Time.time > timeToLiveUntil) //kill bullet when TTL ends
            {
                KillBullet();
                return;
            }

            // bullet collision block
            {
                //reset our hit variables to default state
                hasPenetrated  = true;
                hasDetonated   = false;
                hasRichocheted = false;
                penTicker      = 0;

                float dist = currentVelocity.magnitude * Time.fixedDeltaTime;
                bulletRay = new Ray(currPosition, currentVelocity);
                var hits = Physics.RaycastAll(bulletRay, dist, 9076737);
                if (hits.Length > 0)
                {
                    var orderedHits = hits.OrderBy(x => x.distance);

                    using (var hitsEnu = orderedHits.GetEnumerator())
                    {
                        while (hitsEnu.MoveNext())
                        {
                            if (!hasPenetrated || hasRichocheted || hasDetonated)
                            {
                                break;
                            }

                            RaycastHit hit     = hitsEnu.Current;
                            Part       hitPart = null;
                            KerbalEVA  hitEVA  = null;

                            try
                            {
                                hitPart = hit.collider.gameObject.GetComponentInParent <Part>();
                                hitEVA  = hit.collider.gameObject.GetComponentUpwards <KerbalEVA>();
                            }
                            catch (NullReferenceException)
                            {
                                Debug.Log("[BDArmory]:NullReferenceException for Ballistic Hit");
                                return;
                            }

                            if (hitEVA != null)
                            {
                                hitPart = hitEVA.part;
                                // relative velocity, separate from the below statement, because the hitpart might be assigned only above
                                if (hitPart?.rb != null)
                                {
                                    impactVelocity = (currentVelocity * dragVelocityFactor
                                                      - (hitPart.rb.velocity + Krakensbane.GetFrameVelocityV3f())).magnitude;
                                }
                                else
                                {
                                    impactVelocity = currentVelocity.magnitude * dragVelocityFactor;
                                }
                                ApplyDamage(hitPart, hit, 1, 1);
                                break;
                            }

                            if (hitPart?.vessel == sourceVessel)
                            {
                                continue;                                   //avoid autohit;
                            }
                            Vector3 impactVector = currentVelocity;
                            if (hitPart?.rb != null)
                            {
                                // using relative velocity vector instead of just bullet velocity
                                // since KSP vessels might move faster than bullets
                                impactVector = currentVelocity * dragVelocityFactor - (hitPart.rb.velocity + Krakensbane.GetFrameVelocityV3f());
                            }

                            float hitAngle = Vector3.Angle(impactVector, -hit.normal);

                            if (CheckGroundHit(hitPart, hit))
                            {
                                CheckBuildingHit(hit);
                                if (!RicochetScenery(hitAngle))
                                {
                                    ExplosiveDetonation(hitPart, hit, bulletRay);
                                    KillBullet();
                                }
                                else
                                {
                                    DoRicochet(hitPart, hit, hitAngle);
                                }
                                return;
                            }

                            //Standard Pipeline Hitpoints, Armor and Explosives

                            impactVelocity = impactVector.magnitude;
                            float anglemultiplier = (float)Math.Cos(Math.PI * hitAngle / 180.0);

                            float penetrationFactor = CalculateArmorPenetration(hitPart, anglemultiplier, hit);

                            if (penetrationFactor >= 2)
                            {
                                //its not going to bounce if it goes right through
                                hasRichocheted = false;
                            }
                            else
                            {
                                if (RicochetOnPart(hitPart, hit, hitAngle, impactVelocity))
                                {
                                    hasRichocheted = true;
                                }
                            }

                            if (penetrationFactor > 1 && !hasRichocheted) //fully penetrated continue ballistic damage
                            {
                                hasPenetrated = true;
                                ApplyDamage(hitPart, hit, 1, penetrationFactor);
                                penTicker += 1;
                                CheckPartForExplosion(hitPart);

                                //Explosive bullets that penetrate should explode shortly after
                                //if penetration is very great, they will have moved on
                                //checking velocity as they would not be able to come out the other side
                                //if (explosive && penetrationFactor < 3 || currentVelocity.magnitude <= 800f)
                                if (explosive)
                                {
                                    //move bullet
                                    transform.position += (currentVelocity * Time.fixedDeltaTime) / 3;

                                    ExplosiveDetonation(hitPart, hit, bulletRay);
                                    hasDetonated = true;
                                    KillBullet();
                                }
                            }
                            else if (!hasRichocheted) // explosive bullets that get stopped by armor will explode
                            {
                                //New method

                                if (hitPart.rb != null)
                                {
                                    float forceAverageMagnitude = impactVelocity * impactVelocity *
                                                                  (1f / hit.distance) * (bulletMass - tntMass);

                                    float accelerationMagnitude =
                                        forceAverageMagnitude / (hitPart.vessel.GetTotalMass() * 1000);

                                    hitPart?.rb.AddForceAtPosition(impactVector.normalized * accelerationMagnitude, hit.point, ForceMode.Acceleration);

                                    if (BDArmorySettings.DRAW_DEBUG_LABELS)
                                    {
                                        Debug.Log("[BDArmory]: Force Applied " + Math.Round(accelerationMagnitude, 2) + "| Vessel mass in kgs=" + hitPart.vessel.GetTotalMass() * 1000 + "| bullet effective mass =" + (bulletMass - tntMass));
                                    }
                                }

                                hasPenetrated = false;
                                ApplyDamage(hitPart, hit, 1, penetrationFactor);
                                ExplosiveDetonation(hitPart, hit, bulletRay);
                                hasDetonated = true;
                                KillBullet();
                            }

                            /////////////////////////////////////////////////////////////////////////////////
                            // penetrated after a few ticks
                            /////////////////////////////////////////////////////////////////////////////////

                            //penetrating explosive
                            //richochets

                            if ((penTicker >= 2 && explosive) || (hasRichocheted && explosive))
                            {
                                //detonate
                                ExplosiveDetonation(hitPart, hit, bulletRay, airDetonation);
                                return;
                            }

                            //bullet should not go any further if moving too slowly after hit
                            //smaller caliber rounds would be too deformed to do any further damage
                            if (currentVelocity.magnitude <= 100 && hasPenetrated)
                            {
                                if (BDArmorySettings.DRAW_DEBUG_LABELS)
                                {
                                    Debug.Log("[BDArmory]: Bullet Velocity too low, stopping");
                                }
                                KillBullet();
                                return;
                            }
                            //we need to stop the loop if the bullet has stopped,richochet or detonated
                            if (!hasPenetrated || hasRichocheted || hasDetonated)
                            {
                                break;
                            }
                        } //end While
                    }     //end enumerator
                }         //end if hits
            }             // end if collision

            //////////////////////////////////////////////////
            //Flak Explosion (air detonation/proximity fuse)
            //////////////////////////////////////////////////

            if (ProximityAirDetonation(distanceFromStart))
            {
                //detonate
                ExplosionFx.CreateExplosion(currPosition, tntMass, explModelPath, explSoundPath, ExplosionSourceType.Bullet, caliber, null, sourceVesselName, null, currentVelocity);
                KillBullet();

                return;
            }

            if (bulletDrop)
            {
                // Gravity???
                var gravity_ = FlightGlobals.getGeeForceAtPosition(transform.position);
                //var gravity_ = Physics.gravity;
                currentVelocity += gravity_ * TimeWarp.deltaTime;
            }

            //move bullet
            transform.position += currentVelocity * Time.fixedDeltaTime;
        }
Esempio n. 22
0
        void DeploySubmunitions()
        {
            missileLauncher.sfAudioSource.PlayOneShot(GameDatabase.Instance.GetAudioClip("BDArmory/Sounds/flare"));
            FXMonger.Explode(part, transform.position + part.rb.velocity * Time.fixedDeltaTime, 0.1f);

            deployed = true;
            if (swapCollidersOnDeploy)
            {
                IEnumerator <Collider> col = part.GetComponentsInChildren <Collider>().AsEnumerable().GetEnumerator();
                while (col.MoveNext())
                {
                    if (col.Current == null)
                    {
                        continue;
                    }
                    col.Current.enabled = !col.Current.enabled;
                }
                col.Dispose();
            }

            missileLauncher.sfAudioSource.priority = 999;

            List <GameObject> .Enumerator sub = submunitions.GetEnumerator();
            while (sub.MoveNext())
            {
                if (sub.Current == null)
                {
                    continue;
                }
                sub.Current.SetActive(true);
                sub.Current.transform.parent = null;
                Vector3   direction = (sub.Current.transform.position - part.transform.position).normalized;
                Rigidbody subRB     = sub.Current.GetComponent <Rigidbody>();
                subRB.isKinematic = false;
                subRB.velocity    = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() +
                                    (UnityEngine.Random.Range(submunitionMaxSpeed / 10, submunitionMaxSpeed) * direction);

                Submunition subScript = sub.Current.AddComponent <Submunition>();
                subScript.enabled          = true;
                subScript.deployed         = true;
                subScript.blastForce       = missileLauncher.GetTntMass();
                subScript.blastHeat        = missileLauncher.blastHeat;
                subScript.blastRadius      = missileLauncher.GetBlastRadius();
                subScript.subExplModelPath = subExplModelPath;
                subScript.subExplSoundPath = subExplSoundPath;
                sub.Current.AddComponent <KSPForceApplier>();
            }

            List <GameObject> .Enumerator fairing = fairings.GetEnumerator();
            while (fairing.MoveNext())
            {
                if (fairing.Current == null)
                {
                    continue;
                }
                Vector3   direction = (fairing.Current.transform.position - part.transform.position).normalized;
                Rigidbody fRB       = fairing.Current.GetComponent <Rigidbody>();
                fRB.isKinematic = false;
                fRB.velocity    = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() + ((submunitionMaxSpeed + 2) * direction);
                fairing.Current.AddComponent <KSPForceApplier>();
                fairing.Current.GetComponent <KSPForceApplier>().drag = 0.2f;
                ClusterBombFairing fairingScript = fairing.Current.AddComponent <ClusterBombFairing>();
                fairingScript.deployed = true;
            }

            fairing.Dispose();

            part.explosionPotential  = 0;
            missileLauncher.HasFired = false;

            part.Destroy();
        }
        private void FixedUpdate()
        {
            //Flight values
            if (!CompatibilityChecker.IsAllCompatible() ||
                !HighLogic.LoadedSceneIsFlight ||
                FlightGlobals.ActiveVessel == null ||
                part.Rigidbody == null)
            {
                return;
            }
            pos     = part.partTransform.position;
            asl     = FlightGlobals.getAltitudeAtPos(pos);
            trueAlt = asl;
            if (vessel.mainBody.pqsController != null)
            {
                double terrainAlt = vessel.pqsAltitude;
                if (!vessel.mainBody.ocean || terrainAlt > 0)
                {
                    trueAlt -= terrainAlt;
                }
            }

            atmPressure = FlightGlobals.getStaticPressure(asl, vessel.mainBody) * PhysicsGlobals.KpaToAtmospheres;
            atmDensity  = part.atmDensity;
            Vector3 velocity = part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f();

            sqrSpeed   = velocity.sqrMagnitude;
            dragVector = -velocity.normalized;

            if (atmDensity > 0)
            {
                CalculateChuteFlux();
            }
            else
            {
                convFlux = 0;
            }

            CalculateSafeToDeployEstimate();

            if (!staged)
            {
                return;
            }
            //Checks if the parachute must disarm
            if (armed)
            {
                part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                if (CanDeploy)
                {
                    armed = false;
                }
            }
            //Parachute deployments
            else
            {
                //Parachutes
                if (CanDeploy)
                {
                    if (IsDeployed)
                    {
                        if (!CalculateChuteTemp())
                        {
                            return;
                        }
                        FollowDragDirection();
                    }

                    part.GetComponentCached(ref rigidbody);
                    switch (DeploymentState)
                    {
                    case DeploymentStates.STOWED:
                    {
                        part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                        if (PressureCheck && RandomDeployment)
                        {
                            PreDeploy();
                        }
                        break;
                    }

                    case DeploymentStates.PREDEPLOYED:
                    {
                        part.AddForceAtPosition(DragForce(0, preDeployedDiameter, 1f / semiDeploymentSpeed),
                                                ForcePosition);
                        if (trueAlt <= deployAltitude && dragTimer.Elapsed.TotalSeconds >= 1f / semiDeploymentSpeed)
                        {
                            Deploy();
                        }
                        break;
                    }

                    case DeploymentStates.DEPLOYED:
                    {
                        part.AddForceAtPosition(DragForce(preDeployedDiameter,
                                                          deployedDiameter,
                                                          1f / deploymentSpeed),
                                                ForcePosition);
                        break;
                    }
                    }
                }
                //Deactivation
                else
                {
                    if (IsDeployed)
                    {
                        Cut();
                    }
                    else
                    {
                        failedTimer.Start();
                        StagingReset();
                    }
                }
            }
        }
Esempio n. 24
0
        // Returns (8.018946, 0.0083341, -5.557827) while clamped to the runway.
        public Vector3 GetFlightForcesWorldSpace()
        {
            Vector3 gForce           = FlightGlobals.getGeeForceAtPosition(KerbalIva.transform.position);
            Vector3 centrifugalForce = FlightGlobals.getCentrifugalAcc(KerbalIva.transform.position, FreeIva.CurrentPart.orbit.referenceBody);
            Vector3 coriolisForce    = FlightGlobals.getCoriolisAcc(FreeIva.CurrentPart.vessel.rb_velocity + Krakensbane.GetFrameVelocityV3f(), FreeIva.CurrentPart.orbit.referenceBody);

            return(gForce + centrifugalForce + coriolisForce);
        }
Esempio n. 25
0
        private void ApplyGravity()
        {
            KerbalIva.GetComponentCached(ref KerbalRigidbody);
            if (Gravity)
            {
                Vector3 gForce           = FlightGlobals.getGeeForceAtPosition(KerbalIva.transform.position);
                Vector3 centrifugalForce = FlightGlobals.getCentrifugalAcc(KerbalIva.transform.position, FreeIva.CurrentPart.orbit.referenceBody);
                Vector3 coriolisForce    = FlightGlobals.getCoriolisAcc(FreeIva.CurrentPart.vessel.rb_velocity + Krakensbane.GetFrameVelocityV3f(), FreeIva.CurrentPart.orbit.referenceBody);

                gForce           = InternalSpace.WorldToInternal(gForce);
                centrifugalForce = InternalSpace.WorldToInternal(centrifugalForce);
                coriolisForce    = InternalSpace.WorldToInternal(coriolisForce);
                flightForces     = gForce + centrifugalForce + coriolisForce;

                KerbalRigidbody.AddForce(gForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(centrifugalForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(coriolisForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(Krakensbane.GetLastCorrection(), ForceMode.VelocityChange);

                if (FreeIva.SelectedObject != null)
                {
                    Rigidbody rbso = FreeIva.SelectedObject.GetComponent <Rigidbody>();
                    if (rbso == null)
                    {
                        rbso = FreeIva.SelectedObject.AddComponent <Rigidbody>();
                    }
                    rbso.AddForce(gForce, ForceMode.Acceleration);
                    rbso.AddForce(centrifugalForce, ForceMode.Acceleration);
                    rbso.AddForce(coriolisForce, ForceMode.Acceleration);
                }
            }
            else
            {
                KerbalRigidbody.velocity = Vector3.zero;
            }
        }
Esempio n. 26
0
        private void FixedUpdate()
        {
            //Flight values
            if (!CompatibilityChecker.IsAllCompatible() || !HighLogic.LoadedSceneIsFlight || FlightGlobals.ActiveVessel == null || this.part.Rigidbody == null)
            {
                return;
            }
            this.pos     = this.part.partTransform.position;
            this.ASL     = FlightGlobals.getAltitudeAtPos(this.pos);
            this.trueAlt = this.ASL;
            if (this.vessel.mainBody.pqsController != null)
            {
                double terrainAlt = this.vessel.pqsAltitude;
                if (!this.vessel.mainBody.ocean || terrainAlt > 0)
                {
                    this.trueAlt -= terrainAlt;
                }
            }
            this.atmPressure = FlightGlobals.getStaticPressure(this.ASL, this.vessel.mainBody) * PhysicsGlobals.KpaToAtmospheres;
            this.atmDensity  = part.atmDensity;
            Vector3 velocity = this.part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f();

            this.sqrSpeed   = velocity.sqrMagnitude;
            this.dragVector = -velocity.normalized;

            if (this.atmDensity > 0)
            {
                CalculateChuteFlux();
            }
            else
            {
                this.convFlux = 0;
            }

            CalculateSafeToDeployEstimate();

            if (!this.staged && GameSettings.LAUNCH_STAGES.GetKeyDown() && this.vessel.isActiveVessel && (this.part.inverseStage == Staging.CurrentStage - 1 || Staging.CurrentStage == 0))
            {
                ActivateRC();
            }

            if (this.staged)
            {
                //Checks if the parachute must disarm
                if (this.armed)
                {
                    this.part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                    if (this.canDeploy)
                    {
                        this.armed = false;
                    }
                }
                //Parachute deployments
                else
                {
                    //Parachutes
                    if (this.canDeploy)
                    {
                        if (this.isDeployed)
                        {
                            if (!CalculateChuteTemp())
                            {
                                return;
                            }
                            FollowDragDirection();
                        }

                        switch (this.deploymentState)
                        {
                        case DeploymentStates.STOWED:
                        {
                            this.part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                            if (this.pressureCheck && this.randomDeployment)
                            {
                                PreDeploy();
                            }
                            break;
                        }

                        case DeploymentStates.PREDEPLOYED:
                        {
                            this.part.Rigidbody.AddForceAtPosition(DragForce(0, this.preDeployedDiameter, 1f / this.semiDeploymentSpeed), this.forcePosition, ForceMode.Force);
                            if (this.trueAlt <= this.deployAltitude && this.dragTimer.elapsed.TotalSeconds >= 1f / this.semiDeploymentSpeed)
                            {
                                Deploy();
                            }
                            break;
                        }

                        case DeploymentStates.DEPLOYED:
                        {
                            this.part.rigidbody.AddForceAtPosition(DragForce(this.preDeployedDiameter, this.deployedDiameter, 1f / this.deploymentSpeed), this.forcePosition, ForceMode.Force);
                            break;
                        }

                        default:
                            break;
                        }
                    }
                    //Deactivation
                    else
                    {
                        if (this.isDeployed)
                        {
                            Cut();
                        }
                        else
                        {
                            this.failedTimer.Start();
                            StagingReset();
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        public void Update()
        {
            if (Input.GetKeyDown(KeyCode.R) && Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.D))
            {
                debugging = !debugging;
            }

            if (FlightGlobals.ready && (FlightGlobals.ActiveVessel != null))
            {
                Ray ray = new Ray();

                if (afx == null)
                {
                    GameObject fx = GameObject.Find("FXLogic");
                    if (fx != null)
                    {
                        afx = fx.GetComponent <AerodynamicsFX>();
                    }
                }

                foreach (var vessel in FlightGlobals.Vessels)
                {
                    if (vessel.packed)
                    {
                        continue;
                    }

                    float atmDensity = (float)FlightGlobals.getAtmDensity(
                        FlightGlobals.getStaticPressure(vessel.findWorldCenterOfMass()));

                    if (atmDensity < 0.0001f)
                    {
                        continue;
                    }

                    float airspeed = (float)vessel.srf_velocity.magnitude;

                    reentryTemperature = ReentryTemperature(airspeed, atmDensity);

                    if (heatEnabled && (afx != null) && afx.FxScalar > 0)
                    {
                        foreach (Part p in vessel.Parts)
                        {
                            ray.direction = (p.Rigidbody.GetPointVelocity(p.transform.position) + Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime).normalized;
                            ray.origin    = p.transform.position;

                            var forwardFacing = !Physics.Raycast(ray, 10);
                            p.temperature = Heating(p, forwardFacing);
                        }
                    }
                }

                if (debugging)
                {
                    maxheat = (from p in FlightGlobals.ActiveVessel.Parts
                               select p.temperature).Max();
                    maxheatfail = (from p in FlightGlobals.ActiveVessel.Parts
                                   select p.temperature / p.maxTemp).Max();
                }
            }
        }
Esempio n. 28
0
        private void FixedUpdate()
        {
            //Flight values
            if (!CompatibilityChecker.IsAllCompatible || !HighLogic.LoadedSceneIsFlight || FlightGlobals.ActiveVessel == null || this.part.Rigidbody == null)
            {
                return;
            }
            this.pos         = this.part.transform.position;
            this.asl         = FlightGlobals.getAltitudeAtPos(this.pos);
            this.trueAlt     = this.vessel.GetTrueAlt(this.asl);
            this.atmPressure = this.vessel.staticPressurekPa * PhysicsGlobals.KpaToAtmospheres;
            this.atmDensity  = this.vessel.atmDensity;
            Vector3 velocity = this.part.Rigidbody.velocity + Krakensbane.GetFrameVelocityV3f();

            this.sqrSpeed   = velocity.sqrMagnitude;
            this.dragVector = -velocity.normalized;
            if (!this.staged && GameSettings.LAUNCH_STAGES.GetKeyDown() && this.vessel.isActiveVessel && (this.part.inverseStage == StageManager.CurrentStage - 1 || StageManager.CurrentStage == 0))
            {
                ActivateRC();
            }
            if (this.deployOnGround && !this.staged)
            {
                if (!this.launched && !this.vessel.LandedOrSplashed)
                {
                    if (!this.vessel.LandedOrSplashed)
                    {
                        //Dampening timer
                        if (!this.launchTimer.IsRunning)
                        {
                            this.launchTimer.Start();
                        }
                        if (this.launchTimer.ElapsedMilliseconds >= 3000)
                        {
                            this.launchTimer.Reset();
                            this.launched = true;
                        }
                    }
                    else if (this.launchTimer.IsRunning)
                    {
                        this.launchTimer.Reset();
                    }
                }
                else if (this.launched && this.vessel.horizontalSrfSpeed >= this.cutSpeed && this.vessel.LandedOrSplashed)
                {
                    ActivateRC();
                }
            }

            if (this.atmDensity > 0)
            {
                this.parachutes.ForEach(p => p.CalculateConvectiveFlux());
            }
            SetSafeToDeploy();

            if (this.staged)
            {
                //Checks if the parachute must disarm
                if (this.armed)
                {
                    this.part.stackIcon.SetIconColor(XKCDColors.LightCyan);
                    if (this.parachutes.Exists(p => p.CanDeploy))
                    {
                        this.armed = false;
                    }
                }
                //Parachute deployments
                else
                {
                    if (this.wait)
                    {
                        CheckForWait();
                        if (this.wait)
                        {
                            this.showMessage = true;
                            return;
                        }
                        this.showMessage = false;
                    }

                    //Parachutes
                    this.parachutes.ForEach(p => p.UpdateParachute());

                    //If all parachutes must be cut
                    if (this.AllMustStop)
                    {
                        GUICut();
                        SetRepack();
                    }

                    //If the parachute can't be deployed
                    if (!this.oneWasDeployed && !RealChuteSettings.Instance.AutoArm)
                    {
                        this.failedTimer.Start();
                        StagingReset();
                    }
                }
            }
        }
Esempio n. 29
0
        void FixedUpdate()
        {
            if (!gameObject.activeInHierarchy)
            {
                return;
            }
            //floating origin and velocity offloading corrections
            if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero())
            {
                transform.position -= FloatingOrigin.OffsetNonKrakensbane;
                prevPosition       -= FloatingOrigin.OffsetNonKrakensbane;
                startPosition      -= FloatingOrigin.OffsetNonKrakensbane;
            }
            distanceFromStart = Vector3.Distance(transform.position, startPosition);

            if (Time.time - startTime < stayTime && transform.parent != null)
            {
                transform.rotation = transform.parent.rotation;
                transform.position = spawnTransform.position;
                //+(transform.parent.rigidbody.velocity*Time.fixedDeltaTime);
            }
            else
            {
                if (transform.parent != null && parentRB)
                {
                    transform.parent = null;
                    rb.isKinematic   = false;
                    rb.velocity      = parentRB.velocity + Krakensbane.GetFrameVelocityV3f();
                }
            }

            if (rb && !rb.isKinematic)
            {
                //physics
                if (FlightGlobals.RefFrameIsRotating)
                {
                    rb.velocity += FlightGlobals.getGeeForceAtPosition(transform.position) * Time.fixedDeltaTime;
                }

                //guidance and attitude stabilisation scales to atmospheric density.
                float atmosMultiplier =
                    Mathf.Clamp01(2.5f *
                                  (float)
                                  FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position),
                                                              FlightGlobals.getExternalTemperature(), FlightGlobals.currentMainBody));

                //model transform. always points prograde
                transform.rotation = Quaternion.RotateTowards(transform.rotation,
                                                              Quaternion.LookRotation(rb.velocity + Krakensbane.GetFrameVelocity(), transform.up),
                                                              atmosMultiplier * (0.5f * (Time.time - startTime)) * 50 * Time.fixedDeltaTime);


                if (Time.time - startTime < thrustTime && Time.time - startTime > stayTime)
                {
                    thrustVector.x = randomThrustDeviation * (1 - (Mathf.PerlinNoise(4 * Time.time, randThrustSeed) * 2)) / massScalar; //this needs to scale w/ rocket mass, or light projectiles will be
                    thrustVector.y = randomThrustDeviation * (1 - (Mathf.PerlinNoise(randThrustSeed, 4 * Time.time) * 2)) / massScalar; //far more affected than heavier ones
                    rb.AddRelativeForce(thrustVector);
                }//0.012/rocketmass - use .012 as baseline, it's the mass of hte hydra, which the randomTurstdeviation was originally calibrated for
            }

            if (Time.time - startTime > thrustTime)
            {
                foreach (var pe in pEmitters)
                {
                    if (pe != null)
                    {
                        pe.emit = false;
                    }
                }
            }
            if (Time.time - startTime > 0.1f + stayTime)
            {
                hasPenetrated = true;
                hasDetonated  = false;
                penTicker     = 0;

                currPosition = transform.position;
                float dist = (currPosition - prevPosition).magnitude;
                RocketRay = new Ray(prevPosition, currPosition - prevPosition);
                var hits = Physics.RaycastAll(RocketRay, dist, 9076737);
                if (hits.Length > 0)
                {
                    var orderedHits = hits.OrderBy(x => x.distance);

                    using (var hitsEnu = orderedHits.GetEnumerator())
                    {
                        while (hitsEnu.MoveNext())
                        {
                            if (!hasPenetrated || hasDetonated)
                            {
                                break;
                            }

                            RaycastHit hit     = hitsEnu.Current;
                            Part       hitPart = null;
                            KerbalEVA  hitEVA  = null;

                            try
                            {
                                hitPart = hit.collider.gameObject.GetComponentInParent <Part>();
                                hitEVA  = hit.collider.gameObject.GetComponentUpwards <KerbalEVA>();
                            }
                            catch (NullReferenceException e)
                            {
                                Debug.LogWarning("[BDArmory.BDArmory]:NullReferenceException for Kinetic Hit: " + e.Message);
                                return;
                            }

                            if (hitEVA != null)
                            {
                                hitPart = hitEVA.part;
                                // relative velocity, separate from the below statement, because the hitpart might be assigned only above
                                if (hitPart.rb != null)
                                {
                                    impactVelocity = (rb.velocity - (hitPart.rb.velocity + Krakensbane.GetFrameVelocityV3f())).magnitude;
                                }
                                else
                                {
                                    impactVelocity = rb.velocity.magnitude;
                                }
                                ProjectileUtils.ApplyDamage(hitPart, hit, 1, 1, caliber, rocketMass, impactVelocity, bulletDmgMult, distanceFromStart, explosive, false, sourceVessel, rocketName);
                                break;
                            }

                            if (hitPart != null && hitPart.vessel == sourceVessel)
                            {
                                continue;                                                     //avoid autohit;
                            }
                            Vector3 impactVector = rb.velocity;
                            if (hitPart != null && hitPart.rb != null)
                            {
                                // using relative velocity vector instead of just rocket velocity
                                // since KSP vessels can easily be moving faster than rockets
                                impactVector = rb.velocity - (hitPart.rb.velocity + Krakensbane.GetFrameVelocityV3f());
                            }

                            float hitAngle = Vector3.Angle(impactVector, -hit.normal);

                            if (ProjectileUtils.CheckGroundHit(hitPart, hit, caliber))
                            {
                                ProjectileUtils.CheckBuildingHit(hit, rocketMass, rb.velocity, bulletDmgMult);
                                Detonate(hit.point, false);
                                return;
                            }

                            impactVelocity = impactVector.magnitude;
                            if (gravitic)
                            {
                                var ME = hitPart.FindModuleImplementing <ModuleMassAdjust>();
                                if (ME == null)
                                {
                                    ME = (ModuleMassAdjust)hitPart.AddModule("ModuleMassAdjust");
                                }
                                ME.massMod  += massMod;
                                ME.duration += BDArmorySettings.WEAPON_FX_DURATION;
                            }
                            if (concussion)
                            {
                                hitPart.rb.AddForceAtPosition(impactVector.normalized * impulse, hit.point, ForceMode.Acceleration);
                                Detonate(hit.point, false);
                                hasDetonated = true;
                                return; //impulse rounds shouldn't penetrate/do damage
                            }
                            float anglemultiplier = (float)Math.Cos(Math.PI * hitAngle / 180.0);

                            float thickness         = ProjectileUtils.CalculateThickness(hitPart, anglemultiplier);
                            float penetration       = ProjectileUtils.CalculatePenetration(caliber, rocketMass, impactVelocity);
                            float penetrationFactor = ProjectileUtils.CalculateArmorPenetration(hitPart, anglemultiplier, hit, penetration, thickness, caliber);
                            if (penetration > thickness)
                            {
                                rb.velocity = rb.velocity * (float)Math.Sqrt(thickness / penetration);
                                if (penTicker > 0)
                                {
                                    rb.velocity *= 0.55f;
                                }
                            }

                            if (penetrationFactor > 1)
                            {
                                hasPenetrated = true;
                                ProjectileUtils.ApplyDamage(hitPart, hit, 1, penetrationFactor, caliber, rocketMass, impactVelocity, bulletDmgMult, distanceFromStart, explosive, false, sourceVessel, rocketName);
                                penTicker += 1;
                                ProjectileUtils.CheckPartForExplosion(hitPart);

                                if (explosive)
                                {
                                    transform.position += (rb.velocity * Time.fixedDeltaTime) / 3;

                                    Detonate(transform.position, false);
                                    hasDetonated = true;
                                }
                            }
                            else // stopped by armor
                            {
                                if (hitPart.rb != null && hitPart.rb.mass > 0)
                                {
                                    float forceAverageMagnitude = impactVelocity * impactVelocity *
                                                                  (1f / hit.distance) * rocketMass;

                                    float accelerationMagnitude =
                                        forceAverageMagnitude / (hitPart.vessel.GetTotalMass() * 1000);

                                    hitPart.rb.AddForceAtPosition(impactVector.normalized * accelerationMagnitude, hit.point, ForceMode.Acceleration);

                                    if (BDArmorySettings.DRAW_DEBUG_LABELS)
                                    {
                                        Debug.Log("[BDArmory.PooledRocket]: Force Applied " + Math.Round(accelerationMagnitude, 2) + "| Vessel mass in kgs=" + hitPart.vessel.GetTotalMass() * 1000 + "| rocket effective mass =" + rocketMass);
                                    }
                                }

                                hasPenetrated = false;
                                ProjectileUtils.ApplyDamage(hitPart, hit, 1, penetrationFactor, caliber, rocketMass, impactVelocity, bulletDmgMult, distanceFromStart, explosive, false, sourceVessel, rocketName);
                                Detonate(hit.point, false);
                                hasDetonated = true;
                            }

                            if (penTicker >= 2)
                            {
                                Detonate(hit.point, false);
                                return;
                            }

                            if (rb.velocity.magnitude <= 100 && hasPenetrated && (Time.time - startTime > thrustTime))
                            {
                                if (BDArmorySettings.DRAW_DEBUG_LABELS)
                                {
                                    Debug.Log("[BDArmory.PooledRocket]: Rocket ballistic velocity too low, stopping");
                                }
                                Detonate(hit.point, false);
                                return;
                            }
                            if (!hasPenetrated || hasDetonated)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0)
            {
                Detonate(currPosition, false);
            }
            prevPosition = currPosition;

            if (Time.time - startTime > lifeTime) // life's 10s, quite a long time for faster rockets
            {
                Detonate(transform.position, true);
            }
            if (distanceFromStart >= maxAirDetonationRange)//rockets are performance intensive, lets cull those that have flown too far away
            {
                Detonate(transform.position, false);
            }
            if (ProximityAirDetonation(distanceFromStart))
            {
                Detonate(transform.position, false);
            }
        }
Esempio n. 30
0
 public void FixedUpdate()
 {
     FixAeroFX(afx);
     frameVelocity = Krakensbane.GetFrameVelocityV3f() - Krakensbane.GetLastCorrection() * TimeWarp.fixedDeltaTime;
 }