Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- public class IDDepot : PartModule
- {
- public bool doItOnce = true;
- //762mmAmmo, 30calAmmo, 50calAmmo, 30mmAmmo, 5inchAmmo, 14inchAmmo
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "AmmoType: ")]
- public string setAmmoTo = "762mmAmmo";
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "AmmoType "), UI_FloatRange(minValue = 1f, maxValue = 2f, stepIncrement = 1f)]
- public float setAmmoNumA = 1f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "AmmoType "), UI_FloatRange(minValue = 3f, maxValue = 4f, stepIncrement = 1f)]
- public float setAmmoNumB = 3f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "AmmoType "), UI_FloatRange(minValue = 4f, maxValue = 5f, stepIncrement = 1f)]
- public float setAmmoNumC = 4f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "AmmoType "), UI_FloatRange(minValue = 6f, maxValue = 6f, stepIncrement = 1f)]
- public float setAmmoNumD = 6f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Fill% "), UI_FloatRange(minValue = 10f, maxValue = 100f, stepIncrement = 10f)]
- public float setAmmoTakePer = 100f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "MaxRnds ")]
- public float maxRounds = 0f;
- [KSPField]
- public float effectiveSpace = 0.1f;
- public float volumeOfDepot = 0f; // cm3
- public float packingOverhead = 1.125f;
- public float launchSaveTimer = 500f;
- [KSPField(isPersistant = true)]
- public string depotSelection = "";
- public bool madeChange = false;
- public float updateAmmoTimer = 5f;
- public int roundSetAmmoTo = 0;
- [KSPField(guiActive = false, isPersistant = true)]
- public double idAmmoAmount;
- [KSPField(guiActive = false, isPersistant = true)]
- public double idAmmoMax;
- public string idAmmoName = "";
- public float maxOrdLength = 0f;
- public float ordLength = 0f;
- public float ordDia = 0f;
- public void Start()
- {
- //PartResourceList rresourceList = this.part.Resources;
- //foreach (PartResource rresource in rresourceList)
- //{
- // if (rresource.resourceName != "IDammo")
- // {
- // }
- //}
- if (depotSelection == "A")
- {
- Fields["setAmmoNumB"].guiActiveEditor = false;
- Fields["setAmmoNumC"].guiActiveEditor = false;
- Fields["setAmmoNumD"].guiActiveEditor = false;
- }
- if (depotSelection == "B")
- {
- Fields["setAmmoNumA"].guiActiveEditor = false;
- Fields["setAmmoNumC"].guiActiveEditor = false;
- Fields["setAmmoNumD"].guiActiveEditor = false;
- }
- if (depotSelection == "C")
- {
- Fields["setAmmoNumA"].guiActiveEditor = false;
- Fields["setAmmoNumB"].guiActiveEditor = false;
- Fields["setAmmoNumD"].guiActiveEditor = false;
- }
- if (depotSelection == "D")
- {
- Fields["setAmmoNumA"].guiActiveEditor = false;
- Fields["setAmmoNumB"].guiActiveEditor = false;
- Fields["setAmmoNumC"].guiActiveEditor = false;
- }
- Collider thisCol = GetComponentInChildren<Collider>();
- if (thisCol != null)
- {
- //print("Found a collider on the depot!");
- volumeOfDepot = (thisCol.bounds.extents.x * 100f) * (thisCol.bounds.extents.y * 100f) * (thisCol.bounds.extents.z * 100f);
- }
- if (volumeOfDepot <= 0f)
- {
- volumeOfDepot = 40000f;
- //print("This depot is " + volumeOfDepot + " cubic cm.");
- }
- if (thisCol.bounds.extents.x > thisCol.bounds.extents.y && thisCol.bounds.extents.x > thisCol.bounds.extents.z)
- {
- //print("X is the largest dimension");
- maxOrdLength = thisCol.bounds.extents.x * 100f;
- }
- else if (thisCol.bounds.extents.y > thisCol.bounds.extents.z)
- {
- //print("Y is the largest dimension");
- maxOrdLength = thisCol.bounds.extents.y * 100f;
- }
- else
- {
- //print("Z is the largest dimension");
- maxOrdLength = thisCol.bounds.extents.z * 100f;
- }
- if (effectiveSpace > 1f) effectiveSpace = 1f;
- }
- public void FixedUpdate()
- {
- //int roundSetAmmoTo = (int)setAmmoNum;
- if (HighLogic.LoadedSceneIsEditor)
- {
- if (depotSelection == "A")
- {
- roundSetAmmoTo = (int)setAmmoNumA;
- }
- if (depotSelection == "B")
- {
- roundSetAmmoTo = (int)setAmmoNumB;
- }
- if (depotSelection == "C")
- {
- roundSetAmmoTo = (int)setAmmoNumC;
- }
- if (depotSelection == "D")
- {
- roundSetAmmoTo = (int)setAmmoNumD;
- }
- if (roundSetAmmoTo == 1)
- {
- setAmmoTo = "762mmAmmo";
- ordLength = 3.81f; // in cm
- ordDia = 0.762f; // in cm
- }
- if (roundSetAmmoTo == 2)
- {
- setAmmoTo = "30calAmmo";
- ordLength = 3.95f;
- ordDia = 0.762f;
- }
- if (roundSetAmmoTo == 3)
- {
- setAmmoTo = "50calAmmo";
- ordLength = 6.475f;
- ordDia = 1.295f;
- }
- if (roundSetAmmoTo == 4)
- {
- setAmmoTo = "30mmAmmo";
- ordLength = 15f;
- ordDia = 3f;
- }
- if (roundSetAmmoTo == 5)
- {
- setAmmoTo = "5inchAmmo";
- ordLength = 63.5f;
- ordDia = 12.7f;
- }
- if (roundSetAmmoTo == 6)
- {
- setAmmoTo = "14inchAmmo";
- ordLength = 180f;
- ordDia = 36f;
- }
- if (ordLength < maxOrdLength)
- {
- maxRounds = ((volumeOfDepot * effectiveSpace) / ((ordLength * ordDia) * packingOverhead));
- }
- else if (ordLength > maxOrdLength)
- {
- maxRounds = 0f;
- }
- if (updateAmmoTimer > 0f)
- {
- updateAmmoTimer--;
- if (updateAmmoTimer <= 0f)
- {
- if (madeChange == false)
- {
- madeChange = true;
- }
- FillTheDepot();
- updateAmmoTimer = 15f;
- }
- }
- }
- }
- public void FillTheDepot()
- {
- PartResourceList rresourceList = this.part.Resources;
- foreach (PartResource rresource in rresourceList)
- {
- if (rresource.resourceName == setAmmoTo)
- {
- if (madeChange == true)
- {
- idAmmoAmount = (double)(maxRounds * (setAmmoTakePer * 0.01f));
- idAmmoMax = (double)maxRounds;
- idAmmoName = setAmmoTo;
- rresource.resourceName = setAmmoTo;
- rresource.amount = Math.Round(idAmmoAmount);
- rresource.maxAmount = Math.Round(idAmmoMax);
- //print("inside the filldepot, number: " + idAmmoAmount + " max: " + idAmmoMax);
- madeChange = false;
- }
- }
- else
- {
- rresource.amount = 0.0d;
- rresource.maxAmount = 0.0d;
- }
- }
- }
- }
- ************************************************************IDDepot
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using System.IO;
- using UnityEngine;
- public class relayIFF : PartModule
- {
- [KSPField(guiActive = true, isPersistant = true)]
- public string setIFF = "";
- [KSPEvent(active = true, guiName = "Fix Damage", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = true)]
- public void showTripFix()
- {
- targetPart thisTPart = GetComponent<targetPart>();
- if (thisTPart != null)
- {
- thisTPart.fixState();
- }
- }
- [KSPEvent(name = "togIFF", active = true, guiActive = true, guiName = "Toggle IFF")]
- public void toggleIFF()
- {
- if (setIFF == "blue")
- {
- setIFF = "red";
- }
- else if (setIFF == "red")
- {
- setIFF = "blue";
- }
- }
- public void OnDestroy()
- {
- List<Vessel> pullBlueList = IFFList.Instance.IFFBlue();
- pullBlueList.Remove(this.vessel);
- List<Vessel> pullRedList = IFFList.Instance.IFFRed();
- pullBlueList.Remove(this.vessel);
- print("A vessel was destroyed, and was removed from the IFF list");
- }
- }
- public class saveIDVessel : PartModule
- {
- public bool saveItNow = false;
- public bool doItOnce = false;
- public bool setTimerOnce = true;
- public float updateAutoSaveTimer = 900f;
- public float launchSaveTimer = 600f;
- public float launchLoadTimer = 150f;
- public float lastLoadTime;
- public float lastSaveTime;
- [KSPField(isPersistant = true)]
- public float lastSavedPartsCount;
- public bool partCountChanged = false;
- public bool saveBypass = false;
- public bool pauseSave = true;
- public bool oneStartLoad = true;
- public bool loadItNow = false;
- [KSPField(isPersistant = true)]
- public bool IDTargetSaved = false;
- [KSPField(isPersistant = true)]
- public string saveFileName;
- public float saveTime;
- public float savePartCPS;
- public targetPart CPSselect;
- public List<targetPart> CPSlist;
- [KSPEvent(active = true, guiName = "Test Filesave", guiActiveUnfocused = true, externalToEVAOnly = false, guiActive = true)]
- public void TrySave()
- {
- saveFileName = this.vessel.vesselName + this.vessel.referenceTransformId + ".txt";
- saveItNow = true;
- doItOnce = true;
- }
- [KSPEvent(active = true, guiName = "Test Fileload", guiActiveUnfocused = true, externalToEVAOnly = false, guiActive = true)]
- public void TryLoad()
- {
- saveFileName = this.vessel.vesselName + this.vessel.referenceTransformId + ".txt";
- loadItNow = true;
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (this.vessel.situation == Vessel.Situations.DOCKED)
- {
- saveBypass = true;
- }
- else saveBypass = false;
- if (this.vessel.horizontalSrfSpeed > 0.4 || this.vessel.verticalSpeed > 1.0)
- {
- saveBypass = true;
- }
- else saveBypass = false;
- if (this.vessel.parts.Count != lastSavedPartsCount && IDTargetSaved == true) // must be true this is an update check/save not an initialization save.
- {
- TrySave();
- IDTargetSaved = true;
- lastSavedPartsCount = this.vessel.parts.Count;
- lastSaveTime = Time.time;
- ScreenMessages.PostScreenMessage(new ScreenMessage("This is a part count change save", 3f, ScreenMessageStyle.UPPER_CENTER));
- //print("This is a part count change save!");
- }
- if (IDTargetSaved == false && this.vessel.isActiveVessel)
- {
- if (launchSaveTimer > 0f)
- {
- launchSaveTimer--;
- if (launchSaveTimer <= 0f)
- {
- TrySave();
- IDTargetSaved = true;
- lastSavedPartsCount = this.vessel.parts.Count;
- lastSaveTime = Time.time;
- ScreenMessages.PostScreenMessage(new ScreenMessage("This is the initial launch save", 4f, ScreenMessageStyle.UPPER_CENTER));
- print("This is the initial launch save");
- }
- }
- }
- if (IDTargetSaved == true && !this.vessel.isActiveVessel && setTimerOnce == true)
- {
- lastSaveTime = Time.time; //don't save... it's already saved... but we still need to capture a point in time to start the save checks.
- TryLoad();
- lastLoadTime = Time.time;
- ScreenMessages.PostScreenMessage(new ScreenMessage("This is a resume-state load for a non controlled vessel", 3f, ScreenMessageStyle.UPPER_CENTER));
- //print("This is a resume-state load for a non controlled vessel");
- setTimerOnce = false;
- }
- if (saveBypass == false)
- {
- if (this.vessel.isActiveVessel && IDTargetSaved == true)
- {
- if (launchLoadTimer > 0f)
- {
- launchLoadTimer--;
- if (launchLoadTimer <= 0f)
- {
- TryLoad();
- lastLoadTime = Time.time;
- //print("This is a timed load, did you just switch to this vessel?");
- }
- }
- }
- else if (!this.vessel.isActiveVessel && IDTargetSaved == true && oneStartLoad == true)
- {
- if (launchLoadTimer > 0f)
- {
- launchLoadTimer--;
- if (launchLoadTimer <= 0f)
- {
- TryLoad();
- lastLoadTime = Time.time;
- oneStartLoad = false;
- }
- }
- }
- if (!this.vessel.isActiveVessel && Vector3.Distance(this.vessel.transform.position, FlightGlobals.ActiveVessel.transform.position) < (Vessel.unloadDistance - 500f) && lastSaveTime < Time.time - 30f && setTimerOnce == false || partCountChanged == true)
- {
- TrySave();
- IDTargetSaved = true;
- lastSavedPartsCount = this.vessel.parts.Count;
- lastSaveTime = Time.time;
- partCountChanged = false;
- //print("This is a timed save for an uncontrolled vessel!");
- //ScreenMessages.PostScreenMessage(new ScreenMessage("This is a timed save for an uncontrolled vessel.", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (!this.vessel.isActiveVessel && Vector3.Distance(this.vessel.transform.position, FlightGlobals.ActiveVessel.transform.position) < (Vessel.loadDistance - 500f) && IDTargetSaved == true && lastLoadTime < Time.time - 120f )
- {
- TryLoad();
- lastLoadTime = Time.time;
- //ScreenMessages.PostScreenMessage(new ScreenMessage("This is a timed load for an uncontrolled vessel.", 3f, ScreenMessageStyle.UPPER_CENTER));
- //print("This is a timed load for an uncontrolled vessel!");
- }
- }
- if (!this.vessel.isActiveVessel)
- {
- if (updateAutoSaveTimer > 0f)
- {
- updateAutoSaveTimer--;
- if (updateAutoSaveTimer <= 0f)
- {
- if (this.vessel.parts.Count != lastSavedPartsCount)
- {
- partCountChanged = true;
- }
- updateAutoSaveTimer = 30f;
- }
- }
- }
- if (saveItNow == true)
- {
- if (doItOnce == true)
- {
- CPSlist = new List<targetPart>();
- int i = 0;
- foreach (Part p in this.vessel.parts)
- {
- CPSselect = p.GetComponent<targetPart>();
- if (CPSselect != null)
- {
- i++;
- savePartCPS = CPSselect.currentPartStructure;
- CPSlist.Add(CPSselect);
- }
- }
- doItOnce = false;
- }
- saveTime = Time.time;
- print(saveFileName);
- System.IO.Directory.CreateDirectory("IDSaveVessels");
- string appPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "IDSaveVessels");
- string finalPath = System.IO.Path.Combine(appPath, saveFileName);
- TextWriter tw = new StreamWriter(finalPath);
- // write lines of text to the file
- tw.WriteLine(saveTime);
- for (int i = 0; i < CPSlist.Count; i++)
- {
- tw.WriteLine(CPSlist[i].currentPartStructure);
- tw.WriteLine(CPSlist[i].fuelLeak);
- tw.WriteLine(CPSlist[i].targetBurnedOut);
- tw.WriteLine(CPSlist[i].targetIsBurning);
- tw.WriteLine(CPSlist[i].torpWaterlinePenetration);
- tw.WriteLine(CPSlist[i].weKnowOrigMass);
- tw.WriteLine(CPSlist[i].targetStructure);
- tw.WriteLine(CPSlist[i].currentMass);
- }
- // close the stream
- tw.Close();
- saveItNow = false;
- }
- if (loadItNow == true)
- {
- float checkNumParts = this.vessel.parts.Count;
- // create reader & open file
- string appPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "IDSaveVessels");
- string readPath = System.IO.Path.Combine(appPath, saveFileName);
- TextReader tr = new StreamReader(readPath);
- string recoverSaveTime = tr.ReadLine();
- float recoveredSaveTime = (float)Convert.ToDouble(recoverSaveTime);
- int i = 0;
- foreach (Part p in this.vessel.parts)
- {
- CPSselect = p.GetComponent<targetPart>();
- if (CPSselect != null)
- {
- i++;
- string recoverCPS = tr.ReadLine();
- string recoverFLeak = tr.ReadLine();
- string recoverTBO = tr.ReadLine();
- string recoverTIB = tr.ReadLine();
- string recoverTWP = tr.ReadLine();
- string recoverWKOM = tr.ReadLine();
- string recoverTS = tr.ReadLine();
- string recoverCM = tr.ReadLine();
- #region convert text readlines to values
- float recoveredCPS = (float)Convert.ToDouble(recoverCPS);
- bool recover2FLeak, recover2TBO, recover2TIB, recover2TWP, recover2WKOM;
- if (recoverFLeak == "True")
- {
- recover2FLeak = true;
- }
- else recover2FLeak = false;
- if (recoverTBO == "True")
- {
- recover2TBO = true;
- }
- else recover2TBO = false;
- if (recoverTIB == "True")
- {
- recover2TIB = true;
- }
- else recover2TIB = false;
- if (recoverTWP == "True")
- {
- recover2TWP = true;
- }
- else recover2TWP = false;
- if (recoverWKOM == "True")
- {
- recover2WKOM = true;
- }
- else recover2WKOM = false;
- float recoveredTS = (float)Convert.ToDouble(recoverTS);
- float recoveredCM = (float)Convert.ToDouble(recoverCM);
- #endregion
- if (recoveredCPS <= 0f)
- {
- CPSselect.currentPartStructure = -123f;
- Debug.Log("found a part that was previously destroyed and is now being loaded!");
- }
- else
- {
- CPSselect.currentPartStructure = recoveredCPS;
- }
- CPSselect.fuelLeak = recover2FLeak;
- CPSselect.targetBurnedOut = recover2TBO;
- CPSselect.targetIsBurning = recover2TIB;
- CPSselect.torpWaterlinePenetration = recover2TWP;
- CPSselect.weKnowOrigMass = recover2WKOM;
- CPSselect.targetStructure = recoveredTS;
- CPSselect.currentMass = recoveredCM;
- CPSselect.thisPartRestored = true;
- }
- else
- {
- TryLoad();
- }
- }
- // close the stream
- tr.Close();
- loadItNow = false;
- }
- }
- }
- }
- **********************************************************IDIFF
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- [KSPAddon(KSPAddon.Startup.Flight, false)]
- public class rangeBooster : MonoBehaviour
- {
- public bool doItOnce = true;
- void Start()
- {
- Vessel.loadDistance = 10250f; //10250f
- Vessel.unloadDistance = 10000f; //10000f
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 8500f;
- v.distanceLandedUnpackThreshold = 8000f;
- v.distancePackThreshold = 8500f;
- v.distanceUnpackThreshold = 8000f;
- }
- }
- }
- public void Update()
- {
- if (Vessel.unloadDistance < 10000f || Vessel.loadDistance < 10250f)
- {
- Vessel.loadDistance = 10250f;
- Vessel.unloadDistance = 10000f;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 8500f;
- v.distanceLandedUnpackThreshold = 8000f;
- v.distancePackThreshold = 8500f;
- v.distanceUnpackThreshold = 8000f;
- }
- }
- }
- }
- }
- *************************************************************** IDrangebooster
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- [KSPAddon(KSPAddon.Startup.Flight, false)]
- public class addDamageModule : MonoBehaviour
- {
- public bool doItOnce = true;
- //bool partsWereChanged = false;
- public targetPart checkThisPart;
- void Start()
- {
- doItOnce = true;
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (doItOnce == true)
- {
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- if (!v.isEVA)
- {
- foreach (Part makeTargetPart in v.Parts)
- {
- try
- {
- checkThisPart = makeTargetPart.GetComponentInChildren<targetPart>();
- }
- catch
- {
- //Debug.Log("There was no targetPart on it! Applying targetPart code to Part!");
- }
- if (checkThisPart == null)
- {
- targetPart tpThis = makeTargetPart.gameObject.AddComponent<targetPart>();
- tpThis.objectType = "targetObj";
- tpThis.weKnowOrigMass = false;
- if (makeTargetPart.name.Contains("Carrier") || makeTargetPart.name.Contains("SSN"))
- {
- Debug.Log("Found an ID Legacy BoatPart, applying structure");
- tpThis.targetHardness = 380f;
- tpThis.targetNotVoid = 0.01f;
- tpThis.targetType = 7f;
- }
- if (makeTargetPart.name.Contains("Warship"))
- {
- Debug.Log("Found an ID Warship, applying structure");
- tpThis.targetHardness = 390f;
- tpThis.targetNotVoid = 0.005f;
- tpThis.targetType = 7f;
- }
- if (makeTargetPart.GetComponentInChildren<ModuleEngines>() == true)
- {
- Debug.Log("Found a stock engine, applying structure");
- tpThis.targetHardness = 350f;
- tpThis.targetNotVoid = 0.85f;
- tpThis.targetType = 5f;
- }
- if (makeTargetPart.GetComponentInChildren<ModuleControlSurface>() == true || makeTargetPart.GetComponentInChildren<Winglet>() == true)
- {
- Debug.Log("Found a stock control surface, applying structure");
- tpThis.targetNotVoid = 0.75f;
- tpThis.targetType = 3f;
- }
- if (makeTargetPart.GetComponentInChildren<CommandPod>() == true)
- {
- Debug.Log("Found a stock command pod, applying structure");
- tpThis.targetHardness = 200f;
- tpThis.targetNotVoid = 0.5f;
- tpThis.targetType = 4f;
- }
- if (makeTargetPart.GetComponentInChildren<Part>() == true)
- {
- Part thisPart = makeTargetPart.GetComponentInChildren<Part>();
- PartResourceList resourceList = thisPart.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel")
- {
- Debug.Log("Found a stock fuel tank, applying structure");
- tpThis.targetNotVoid = 0.5f;
- tpThis.targetType = 6f;
- }
- }
- }
- if (makeTargetPart.name.Contains("FSbomb"))
- {
- Debug.Log("Found a FS Bomber part.");
- tpThis.targetNotVoid = 0.075f;
- tpThis.targetHardness = 170f;
- tpThis.targetType = 7f;
- }
- if (makeTargetPart.name.Contains("RepairStation"))
- {
- Debug.Log("Found a RepairStation part.");
- tpThis.targetNotVoid = 0.15f;
- tpThis.targetHardness = 220f;
- tpThis.targetType = 8f;
- }
- }
- }
- }
- }
- doItOnce = false;
- }
- }
- }
- public void Update()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (FlightGlobals.ActiveVessel.verticalSpeed <= 0.5 && FlightGlobals.ActiveVessel.horizontalSrfSpeed <= 0.5)
- {
- checkIsTarget();
- }
- }
- }
- public void checkIsTarget()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- foreach (Part makeTargetPart in v.Parts)
- {
- if (!makeTargetPart.GetComponent<targetPart>())
- {
- //Debug.Log("There was no targetPart on it! Applying targetPart code to Part!");
- targetPart tpThis = makeTargetPart.gameObject.AddComponent<targetPart>();
- tpThis.objectType = "targetObj";
- tpThis.firstRun = true;
- tpThis.weKnowOrigMass = false;
- if (makeTargetPart.GetComponentInChildren<ModuleEngines>() == true)
- {
- Debug.Log("Found a stock engine, applying structure");
- tpThis.targetHardness = 350f;
- tpThis.targetNotVoid = 1f;
- tpThis.targetType = 5f;
- }
- if (makeTargetPart.GetComponentInChildren<ModuleControlSurface>() == true || makeTargetPart.GetComponentInChildren<Winglet>() == true)
- {
- Debug.Log("Found a stock control surface, applying structure");
- tpThis.targetNotVoid = 0.75f;
- tpThis.targetType = 3f;
- }
- if (makeTargetPart.GetComponentInChildren<CommandPod>() == true)
- {
- Debug.Log("Found a stock command pod, applying structure");
- tpThis.targetNotVoid = 0.5f;
- tpThis.targetType = 4f;
- }
- if (makeTargetPart.GetComponentInChildren<Part>() == true)
- {
- Part thisPart = makeTargetPart.GetComponentInChildren<Part>();
- PartResourceList resourceList = thisPart.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel")
- {
- Debug.Log("Found a stock fuel tank, applying structure");
- tpThis.targetNotVoid = 0.4f;
- tpThis.targetType = 6f;
- }
- }
- }
- if (makeTargetPart.name.Contains("FSbomb"))
- {
- Debug.Log("Found a FS Bomber part.");
- tpThis.targetNotVoid = 0.075f;
- tpThis.targetHardness = 170f;
- tpThis.targetType = 7f;
- }
- }
- }
- }
- }
- }
- }
- [KSPAddon(KSPAddon.Startup.Flight, false)]
- public class IFFList : MonoBehaviour
- {
- public bool doItOnce = true;
- public targetPart checkThisPart;
- public static IFFList Instance = null;
- public int lastVesselCount;
- public float updateListTimer = 900f;
- //public List
- private List<Vessel> getAllIFFRed = new List<Vessel>();
- private List<Vessel> getAllIFFBlue = new List<Vessel>();
- public List<Vessel> IFFRed()
- {
- return Instance.getAllIFFRed;
- }
- public List<Vessel> IFFBlue()
- {
- return Instance.getAllIFFBlue;
- }
- public void Awake()
- {
- Instance = this;
- lastVesselCount = 0;
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (FlightGlobals.Vessels.Count != lastVesselCount)
- {
- alterTheLists();
- lastVesselCount = FlightGlobals.Vessels.Count;
- }
- if (updateListTimer > 0f)
- {
- updateListTimer--;
- if (updateListTimer <= 0f)
- {
- alterTheLists();
- updateListTimer = 300f;
- }
- }
- }
- }
- public void alterTheLists()
- {
- getAllIFFBlue.Clear();
- getAllIFFRed.Clear();
- foreach (Vessel aVessel in FlightGlobals.Vessels)
- {
- foreach (Part aPart in aVessel.Parts)
- {
- foreach (PartModule aModule in aPart.Modules)
- {
- if (aModule is relayIFF)
- {
- relayIFF thisIFF = aModule.GetComponent<relayIFF>();
- if (thisIFF.setIFF == "red")
- {
- if (!getAllIFFRed.Contains(thisIFF.vessel))
- {
- getAllIFFRed.Add(thisIFF.vessel);//place it
- }
- if (getAllIFFBlue.Contains(thisIFF.vessel))
- {
- getAllIFFBlue.Remove(thisIFF.vessel);
- }
- }
- if (thisIFF.setIFF == "blue")
- {
- if (!getAllIFFBlue.Contains(thisIFF.vessel))
- {
- getAllIFFBlue.Add(thisIFF.vessel);
- }
- if (getAllIFFRed.Contains(thisIFF.vessel))
- {
- getAllIFFRed.Remove(thisIFF.vessel);//place it
- }
- }
- }
- }
- }
- }
- lastVesselCount = FlightGlobals.Vessels.Count;
- }
- }
- ******************************************************************IDbaseweapons
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- public class IDHardPoint : PartModule
- {
- public Transform hardPoint;
- public Transform[] multiPoints;
- public bool doItOnce = true;
- public bool sAWHSafe = true;
- [KSPField(guiActive = false, isPersistant = true)]
- public bool isRocketPod = false;
- [KSPField(guiActive = false, isPersistant = true)]
- public float podRockets = 1f;
- [KSPField(guiActive = false, isPersistant = true)]
- public float rocPodSize = 1f;
- [KSPField(guiActive = false, isPersistant = true)]
- public string ordPath = "IDSkillfulR1/Parts/IDMk82Bomb/model";
- [KSPField(guiActive = false, isPersistant = true)]
- public string ordType = "Nil";
- [KSPField(guiActive = false, isPersistant = true)]
- public bool isStandalone = false;
- public int chosenOrd = 0;
- public bool ordChanged = false;
- public int chosenWHead = 1;
- public int numOfOrdTypes = 7;
- public int numOfRocTypes = 3;
- public int numOfWHTypes = 3;
- public float partRadius;
- public GameObject ordinanceInstance;
- public GameObject[] multiInstances;
- public Vector3 thisWayUp;
- [KSPField(guiActive = true, isPersistant = true)]
- public string loadedName = "Nil";
- [KSPField(guiActive = false, isPersistant = true)]
- public float emptyMass = 0f;
- [KSPField(guiActive = false, isPersistant = true)]
- public float emptyMDrag = 0f;
- [KSPField(guiActive = false, isPersistant = true)]
- public float emptyDrag = 0f;
- [KSPField(guiActive = false, isPersistant = true)]
- public float emptyADrag = 0f;
- [KSPField(guiActive = false, isPersistant = true)]
- public bool getEmptyValues = true;
- public float ordMass, ordDrag, ordMDrag, ordADrag, ordRDelay, ordRDrag;
- public float ordHardness;
- public bool ordIsRetarded, ordIsAirBurst, ordIsClusterBomb, ordIsTorpedo, ordIsRocket;
- [KSPField]
- public float ordTorpThrust = 5f;
- [KSPField]
- public float ordTorpRTimer = 5000f;
- [KSPField]
- public float ordRocSize = 1f;
- [KSPField(guiActive = false, isPersistant = true)]
- public float warheadType = 1f;
- [KSPField(guiActive = true, isPersistant = true)]
- public string showWHType = "HE";
- public double ordBurstAlt;
- public int ordClusterBomblets;
- [KSPField(guiActive = false, isPersistant = true)]
- public bool bombLoaded = false;
- public GameObject bombCollider;
- public bool bombsAway = false;
- public bool onePack = true;
- public Transform sendHoldHeading;
- public bool positionChanged = false;
- [KSPEvent(name = "chooseWHead", active = true, guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, guiActiveEditor = true, unfocusedRange = 5f, guiName = "Choose Warhead")]
- public void letsChooseWarhead()
- {
- chosenWHead += 1;
- if (chosenWHead > numOfWHTypes) chosenWHead = 1;
- if (chosenWHead == 1)
- {
- showWHType = "HE";
- ScreenMessages.PostScreenMessage(new ScreenMessage("HE - High Explosive", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenWHead == 2)
- {
- showWHType = "Incen.";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Incendiary", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenWHead == 3)
- {
- showWHType = "AP";
- ScreenMessages.PostScreenMessage(new ScreenMessage("AP - Armour Piercing", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- warheadType = (float)chosenWHead;
- }
- [KSPEvent(name = "chooseOrd", active = true, guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, guiActiveEditor = true, unfocusedRange = 5f, guiName = "Choose Ordnance")]
- public void letsChooseOrd()
- {
- ordChanged = true;
- if (!isRocketPod)
- {
- chosenOrd += 1;
- if (chosenOrd > numOfOrdTypes) chosenOrd = 1;
- if (chosenOrd == 1)
- {
- ordPath = "";
- ordType = "Nil";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Hardpoint Empty!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 2)
- {
- ordPath = "IDSkillfulR1/Parts/IDWW1Bomb/model";
- ordType = "WW1Bomb125lb";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with WW1 125lb Bomb", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 3)
- {
- ordPath = "IDSkillfulR1/Parts/IDWW1Bomb/model";
- ordType = "WW1Bomb250lb";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with WW1 250lb Bomb", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 4)
- {
- ordPath = "IDSkillfulR1/Parts/IDMk84Bomb/model";
- ordType = "Mk82Cluster";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with Mk82 500lb Bomb", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 5)
- {
- ordPath = "IDSkillfulR1/Parts/IDMk84Bomb/model";
- ordType = "Mk84Retarded";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with Mk84 2000lb Bomb", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 6)
- {
- ordPath = "IDSkillfulR1/Parts/IDMk84Bomb/model";
- ordType = "TallBoy";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with 12000lb TallBoy Bomb", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 7)
- {
- ordPath = "IDSkillfulR1/Parts/IDType91T/model";
- ordType = "Type91T";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with Type 91t Torpedo", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- else
- {
- chosenOrd += 1;
- if (chosenOrd > numOfRocTypes) chosenOrd = 1;
- if (chosenOrd == 1)
- {
- ordPath = "";
- ordType = "Nil";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Hardpoint Empty!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 2)
- {
- ordPath = "IDSkillfulR1/Parts/IDlau68Rocket/model";
- ordType = "lau68Rocket";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with lau68 Rockets", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (chosenOrd == 3 && rocPodSize > 1f)
- {
- ordPath = "IDSkillfulR1/Parts/IDlau68Rocket/model";
- ordType = "hellfireRocket";
- ScreenMessages.PostScreenMessage(new ScreenMessage("Load with Hellfire Rocket", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- }
- [KSPEvent(name = "loadHardPoint", active = true, guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, guiActiveEditor = true, unfocusedRange = 5f, guiName = "Load Ordnance")]
- public void letsLoadHardPoint()
- {
- doBombSet();
- }
- [KSPEvent(name = "triggerBombDrop", active = true, guiActive = true, guiName = "Release")]
- public void doDropBomb()
- {
- if (bombLoaded == true)
- {
- bombsAway = true;
- }
- if (bombLoaded == false)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("No Bomb on Hardpoint!", 4f, ScreenMessageStyle.UPPER_CENTER));
- //print("No Bomb on Hardpoint!");
- }
- }
- [KSPAction("Release Bomb")]
- public void actBombDrop(KSPActionParam param)
- {
- doDropBomb();
- }
- public override void OnStart(StartState state)
- {
- base.OnStart(state);
- if (podRockets > 1f && isRocketPod == true)
- {
- multiPoints = this.part.FindModelTransforms("loadPoint");
- //print("Found enough locations for " + multiPoints.Count() + " rockets!");
- if (getEmptyValues == true && multiPoints.Count() > 1)
- {
- emptyDrag = this.part.minimum_drag;
- emptyMass = this.part.mass;
- emptyMDrag = this.part.maximum_drag;
- emptyADrag = this.part.angularDrag;
- getEmptyValues = false;
- }
- }
- else
- {
- if (hardPoint == null)
- {
- try
- {
- hardPoint = this.part.FindModelTransform("loadPoint");
- }
- catch
- {
- print("Problem locating loadPoint!");
- }
- if (getEmptyValues == true && hardPoint != null)
- {
- emptyDrag = this.part.minimum_drag;
- emptyMass = this.part.mass;
- emptyMDrag = this.part.maximum_drag;
- emptyADrag = this.part.angularDrag;
- getEmptyValues = false;
- }
- }
- }
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- #region Standalone Warhead
- //if (isStandalone == true && doItOnce == false && sAComponent != null && sAComponent.transform.parent != null)
- //{
- // if (this.transform.position != sAComponent.transform.position)
- // {
- // sAComponent.transform.position = this.transform.position + transform.forward * 8f;
- // sAComponent.transform.rotation = this.transform.rotation;
- // //sAComponent.transform.parent = this.part.transform;
- // }
- // if (rigidbody == null)
- // {
- // Rigidbody rb = sAComponent.AddComponent<Rigidbody>();
- // rb.detectCollisions = true;
- // rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- // rb.mass = this.part.mass;
- // rb.drag = rndNumber.rndFloat(0.1f, 0.25f);
- // rb.collider.isTrigger = true;
- // }
- //}
- //if (isStandalone == true && doItOnce == true && sAWHSafe == false)
- //{
- // //not implemented yet, requires instantiating a trigger collider/rigidbody to the front of the vessel...
- // //can't remove rigidbodies with joints, and the stock rigidbody/collider structure will not work with skillful.
- // if (sAComponent == null)
- // {
- // sAComponent = GameObject.CreatePrimitive(PrimitiveType.Cube);
- // sAComponent.SetActive(true);
- // sAComponent.renderer.enabled = true;
- // sAComponent.transform.localScale = new Vector3(4f, 4f, 1f); // gameObject.transform.localScale.Set(0.05f, 0.05f, 0.05f);
- // sAComponent.transform.position = this.transform.position + transform.forward * 8f;
- // sAComponent.transform.rotation = this.transform.rotation;
- // sAComponent.transform.parent = this.part.transform;
- // Rigidbody rb = sAComponent.AddComponent<Rigidbody>();
- // rb.detectCollisions = true;
- // rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- // rb.mass = this.part.mass;
- // rb.drag = rndNumber.rndFloat(0.1f, 0.25f);
- // }
- // IDDropBomb bombPart = this.gameObject.AddComponent<IDDropBomb>();
- // //print("added IDbombdrop");
- // bombPart.isRetarded = ordIsRetarded;
- // bombPart.retardDelay = ordRDelay;
- // bombPart.retardDrag = ordRDrag;
- // bombPart.isAirBurst = ordIsAirBurst;
- // bombPart.burstAlt = ordBurstAlt;
- // bombPart.isClusterBomb = ordIsClusterBomb;
- // bombPart.isTorpedo = ordIsTorpedo;
- // bombPart.isRocket = ordIsRocket;
- // bombPart.holdTorpHeading = sendHoldHeading;
- // bombPart.torpedoLifeTimer = ordTorpRTimer;
- // bombPart.torpedoThrust = ordTorpThrust;
- // bombPart.clusterBomblets = ordClusterBomblets;
- // bombPart.isHardness = ordHardness;
- // bombPart.isWarheadType = warheadType;
- // doItOnce = false;
- //}
- #endregion
- thisWayUp = (this.transform.position - FlightGlobals.ActiveVessel.mainBody.position).normalized;
- if (hardPoint != null && podRockets <= 1f || multiPoints.Count() > 1 && podRockets > 1f)
- {
- if (bombLoaded == true && loadedName != "Nil" && doItOnce == true || bombLoaded == true && ordChanged == true)
- {
- doItOnce = false;
- doBombSet();
- ordChanged = false;
- if (showWHType == "HE")
- {
- warheadType = 1f;
- }
- if (showWHType == "Incen.")
- {
- warheadType = 2f;
- }
- if (showWHType == "AP")
- {
- warheadType = 3f;
- }
- }
- if (bombsAway == true)
- {
- bombsAway = false;
- bombLoaded = false;
- onePack = true;
- if (loadedName != "Nil")
- {
- loadedName = "Nil";
- this.part.mass = emptyMass;
- this.part.maximum_drag = emptyMDrag;
- this.part.minimum_drag = emptyDrag;
- this.part.angularDrag = emptyADrag;
- }
- if (podRockets < 2f || !isRocketPod)
- {
- Rigidbody ordRigidB = ordinanceInstance.AddComponent<Rigidbody>();
- if (ordinanceInstance.rigidbody != null)
- {
- ordRigidB.velocity = this.vessel.rigidbody.velocity;
- ordRigidB.mass = ordMass;
- ordRigidB.drag = ordMDrag;
- ordRigidB.angularDrag = ordADrag;
- ordRigidB.detectCollisions = true;
- ordRigidB.collisionDetectionMode = CollisionDetectionMode.Continuous;
- if (ordIsRocket == true)
- {
- ordRigidB.useGravity = false;
- }
- }
- sendHoldHeading = hardPoint;
- IDDropBomb bombPart = ordinanceInstance.AddComponent<IDDropBomb>();
- bombPart.isRetarded = ordIsRetarded;
- bombPart.retardDelay = ordRDelay;
- bombPart.retardDrag = ordRDrag;
- bombPart.isAirBurst = ordIsAirBurst;
- bombPart.burstAlt = ordBurstAlt;
- bombPart.isClusterBomb = ordIsClusterBomb;
- bombPart.isTorpedo = ordIsTorpedo;
- bombPart.isRocket = ordIsRocket;
- bombPart.holdTorpHeading = sendHoldHeading;
- bombPart.torpedoLifeTimer = ordTorpRTimer;
- bombPart.torpedoThrust = ordTorpThrust;
- bombPart.clusterBomblets = ordClusterBomblets;
- bombPart.isHardness = ordHardness;
- bombPart.isWarheadType = warheadType;
- ordinanceInstance.transform.parent = null;
- }
- if (multiPoints.Count() > 1)
- {
- foreach (GameObject rocketObj in multiInstances)
- {
- Rigidbody ordRigidB = rocketObj.AddComponent<Rigidbody>();
- if (rocketObj.rigidbody != null)
- {
- ordRigidB.velocity = this.vessel.rigidbody.velocity;
- ordRigidB.mass = ordMass;
- ordRigidB.drag = ordMDrag;
- ordRigidB.angularDrag = ordADrag;
- ordRigidB.detectCollisions = true;
- ordRigidB.collisionDetectionMode = CollisionDetectionMode.Continuous;
- if (ordIsRocket == true)
- {
- ordRigidB.useGravity = false;
- }
- }
- sendHoldHeading = multiPoints[0];
- IDDropBomb bombPart = rocketObj.AddComponent<IDDropBomb>();
- bombPart.isRetarded = ordIsRetarded;
- bombPart.retardDelay = ordRDelay;
- bombPart.retardDrag = ordRDrag;
- bombPart.isAirBurst = ordIsAirBurst;
- bombPart.burstAlt = ordBurstAlt;
- bombPart.isClusterBomb = ordIsClusterBomb;
- bombPart.isTorpedo = ordIsTorpedo;
- bombPart.isRocket = ordIsRocket;
- bombPart.holdTorpHeading = sendHoldHeading;
- bombPart.torpedoLifeTimer = ordTorpRTimer;
- bombPart.torpedoThrust = ordTorpThrust;
- bombPart.clusterBomblets = ordClusterBomblets;
- bombPart.isHardness = ordHardness;
- bombPart.isWarheadType = warheadType;
- rocketObj.transform.parent = null;
- }
- }
- }
- }
- }
- }
- public void doBombSet()
- {
- bool stopRepet = true;
- if (bombLoaded == true && loadedName != ordType)
- {
- //print("in here1");
- if (ordinanceInstance != null)
- {
- Destroy(ordinanceInstance);
- foreach (GameObject i in multiInstances)
- {
- Destroy(i);
- onePack = true;
- }
- }
- }
- if (ordinanceInstance == null && ordType != "Nil")
- {
- //print("in here2");
- if (isRocketPod && podRockets > 1f && onePack == true) //&& bombLoaded == false
- {
- //print("in here3");
- int i = 0;
- multiInstances = new GameObject[(int)podRockets];
- foreach (Transform tR in multiPoints)
- {
- try
- {
- multiInstances[i] = GameDatabase.Instance.GetModel(ordPath);
- }
- catch
- {
- print("Problem locating loadPoint!");
- }
- if (multiInstances[i] != null && stopRepet == true)
- {
- //print("in here4");
- if (ordType == "lau68Rocket")
- {
- loadedName = "lau68Rocket";
- ordMass = 0.008f;
- ordHardness = 420f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.7f;
- ordMDrag = 0.7f;
- ordADrag = 1f;
- partRadius = 0.015f; //0.01625f
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = true;
- ordRocSize = 1f;
- ordTorpThrust = 1.4f;
- ordTorpRTimer = 500f;
- }
- multiInstances[i].SetActive(true);
- multiInstances[i].transform.position = tR.position - (tR.up.normalized * partRadius);
- multiInstances[i].transform.rotation = tR.rotation;
- multiInstances[i].transform.parent = this.part.transform;
- }
- if (i == (int)podRockets)
- {
- stopRepet = false;
- }
- i++;
- }
- bombLoaded = true;
- onePack = false;
- }
- else
- {
- //print("in here5");
- try
- {
- ordinanceInstance = GameDatabase.Instance.GetModel(ordPath);
- }
- catch
- {
- print("Problem locating loadPoint!");
- }
- if (ordinanceInstance != null)
- {
- if (ordType == "WW1Bomb125lb")
- {
- loadedName = "WW1Bomb125lb";
- ordinanceInstance.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
- ordMass = 0.0625f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 0.8f;
- partRadius = 0.1f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 250.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- if (ordType == "WW1Bomb250lb")
- {
- loadedName = "WW1Bomb250lb";
- ordinanceInstance.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f);
- ordMass = 0.125f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 0.8f;
- partRadius = 0.125f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 250.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- if (ordType == "Mk82Cluster")
- {
- loadedName = "Mk82Cluster";
- ordinanceInstance.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f); // this bomb uses the same model but at 75% the size.
- ordMass = 0.25f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 1f;
- partRadius = 0.16f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 250.0;
- ordIsClusterBomb = true;
- ordClusterBomblets = 24;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- if (ordType == "Mk84Retarded")
- {
- loadedName = "Mk84Retarded";
- ordinanceInstance.transform.localScale = new Vector3(1f, 1f, 1f);
- ordMass = 1f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 1f;
- partRadius = 0.2765f;
- ordIsRetarded = true;
- ordRDelay = 1f;
- ordRDrag = 0.5f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- if (ordType == "TallBoy")
- {
- loadedName = "TallBoy";
- ordinanceInstance.transform.localScale = new Vector3(2f, 2f, 2f);
- ordMass = 5.4f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 1f;
- partRadius = 0.485f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- if (ordType == "Type91T")
- {
- loadedName = "Type91T";
- ordMass = 1.12f;
- ordHardness = 350f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.2f;
- ordMDrag = 0.3f;
- ordADrag = 1f;
- partRadius = 0.325f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = true;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 9f;
- ordTorpRTimer = 7500f;
- }
- if (ordType == "lau68Rocket")
- {
- loadedName = "lau68Rocket";
- ordMass = 0.008f;
- ordHardness = 420f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.7f;
- ordMDrag = 0.7f;
- ordADrag = 1f;
- partRadius = 0.015f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = true;
- ordRocSize = 1f;
- ordTorpThrust = 1.4f;
- ordTorpRTimer = 500f;
- }
- if (ordType == "hellfireRocket")
- {
- loadedName = "hellfireRocket";
- ordinanceInstance.transform.localScale = new Vector3(2f, 2f, 2f);
- ordMass = 0.085f;
- ordHardness = 415f;
- warheadType = (float)chosenWHead;
- ordDrag = 0.7f;
- ordMDrag = 0.7f;
- ordADrag = 0.9f;
- partRadius = 0.125f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0.0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = true;
- ordRocSize = 2f;
- ordTorpThrust = 15f;
- ordTorpRTimer = 800f;
- }
- ordinanceInstance.SetActive(true);
- ordinanceInstance.transform.position = hardPoint.position - (hardPoint.up.normalized * partRadius);
- ordinanceInstance.transform.rotation = hardPoint.rotation;
- ordinanceInstance.transform.parent = this.part.transform;
- bombLoaded = true;
- }
- }
- }
- if (ordType == "Nil")
- {
- bombLoaded = false;
- loadedName = "Nil";
- ordMass = 0f;
- ordHardness = 0f;
- warheadType = 0f;
- ordDrag = 0f;
- ordMDrag = 0f;
- ordADrag = 0f;
- partRadius = 0f;
- ordIsRetarded = false;
- ordRDelay = 0f;
- ordRDrag = 0f;
- ordIsAirBurst = false;
- ordBurstAlt = 0;
- ordIsClusterBomb = false;
- ordClusterBomblets = 0;
- ordIsTorpedo = false;
- ordIsRocket = false;
- ordRocSize = 0f;
- ordTorpThrust = 0f;
- ordTorpRTimer = 0f;
- }
- this.part.mass = emptyMass + ordMass;
- this.part.maximum_drag = emptyMDrag + ordMDrag;
- this.part.minimum_drag = emptyDrag + ordDrag;
- this.part.angularDrag = emptyADrag + ordADrag;
- if (isRocketPod && podRockets > 1f)
- {
- this.part.mass = emptyMass + (ordMass * podRockets);
- }
- }
- }
- class IDDropBomb : MonoBehaviour
- {
- public String targetVessel = "None";
- public Transform thrustPoint;
- public GameObject rocketSmokeFX;
- public float maxTorque = 1200f;
- public bool isSafe = true;
- public bool zeroVelOnce = true;
- [KSPField]
- public float timerGoBoom = 150f;
- public float septimer = 0f;
- public bool waitPeriod = true;
- [KSPField]
- public bool isRetarded = false;
- [KSPField]
- public float retardDelay = 1f;
- [KSPField]
- public float retardDrag = 2f;
- [KSPField]
- public bool isClusterBomb = false;
- [KSPField]
- public int clusterBomblets = 16;
- [KSPField]
- public bool isAirBurst = false;
- [KSPField]
- public bool isTorpedo = false;
- public bool splashSet = true;
- public bool tGuided = true;
- public Quaternion headingT;
- [KSPField]
- public bool isRocket = false;
- public float rocketSSS = 0.005f;
- [KSPField]
- public double runDepth = -1.5;
- public Transform holdTorpHeading;
- public float torpedoThrust = 5f;
- [KSPField]
- public double burstAlt = 250.0d;
- public float isWarheadType = 0f;
- public float torpedoLifeTimer = 5000f;
- public float origTLT;
- public float isHardness = 250f;
- private bool oneExplosion = true;
- public double partAltitude = 0.0d;
- private float explosionPower, blastRadius;
- private bool doItOnce = true;
- private bool burstOnce = true;
- public AudioSource soundDrop;
- public Vector3 thisWayUp;
- private float _inertia;
- void Awake()
- {
- if (rigidbody != null)
- {
- _inertia = Mathf.Max(rigidbody.inertiaTensor.x, rigidbody.inertiaTensor.y, rigidbody.inertiaTensor.z);
- }
- }
- public void Start()
- {
- if (isRocket)
- {
- if (thrustPoint == null)
- {
- try
- {
- Transform[] findTP = this.gameObject.GetComponents<Transform>();
- foreach (Transform t in findTP)
- {
- if (t.name.Contains("thrustTransform"))
- {
- thrustPoint = t;
- }
- }
- }
- catch
- {
- print("Problem locating thrustTransform!");
- }
- if (thrustPoint != null)
- {
- print("Found the Rocket Thrustpoint");
- }
- }
- }
- #region Sound effects
- if (!isRocket && septimer == 0f)
- {
- if (!GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/bombDrop")) return;
- soundDrop = this.gameObject.AddComponent<AudioSource>();
- if (soundDrop.audio != null)
- {
- soundDrop.audio.volume = GameSettings.SHIP_VOLUME;
- soundDrop.audio.rolloffMode = AudioRolloffMode.Linear;
- soundDrop.audio.dopplerLevel = 0f;
- soundDrop.audio.panLevel = 1f;
- soundDrop.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/bombDrop");
- soundDrop.audio.loop = false;
- soundDrop.audio.playOnAwake = false;
- soundDrop.audio.priority = 2;
- }
- }
- if(isRocket && septimer == 0f)
- {
- if (!GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/IDRocket")) return;
- soundDrop = this.gameObject.AddComponent<AudioSource>();
- if (soundDrop.audio != null)
- {
- soundDrop.audio.volume = GameSettings.SHIP_VOLUME;
- soundDrop.audio.rolloffMode = AudioRolloffMode.Linear;
- soundDrop.audio.dopplerLevel = 0f;
- soundDrop.audio.panLevel = 1f;
- soundDrop.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDRocket");
- soundDrop.audio.loop = true;
- soundDrop.audio.playOnAwake = false;
- soundDrop.audio.priority = 2;
- }
- }
- #endregion
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (doItOnce == true)
- {
- this.gameObject.SetActive(true);
- setColliderStateInChildren(this.gameObject, true);
- septimer = 0f;
- if (isRocket)
- {
- explosionPower = rigidbody.mass * 100f;
- }
- else
- {
- explosionPower = rigidbody.mass * 500f;
- }
- blastRadius = explosionPower * 0.25f;
- doItOnce = false;
- }
- partAltitude = Vector3.Distance(this.rigidbody.transform.position, FlightGlobals.ActiveVessel.mainBody.position) - (float)FlightGlobals.ActiveVessel.mainBody.Radius;
- thisWayUp = (this.transform.position - FlightGlobals.ActiveVessel.mainBody.position).normalized;
- if (this.partAltitude < -3.0)
- {
- if (splashSet == true)
- {
- //print("Hit the water!");
- FXMonger.Splash(this.transform.position, this.rigidbody.velocity.magnitude * this.rigidbody.mass);
- splashSet = false;
- }
- if (!isTorpedo)
- {
- GameObject fxSplashInstance = new GameObject();
- try
- {
- fxSplashInstance = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/largeSplash/model");
- }
- catch
- {
- print("Problem locating largeSplash");
- }
- if (fxSplashInstance != null)
- {
- fxSplashInstance.SetActive(true);
- fxSplashInstance.transform.parent = null;
- fxSplashInstance.transform.position = this.transform.position;
- fxSplashInstance.transform.rotation = Quaternion.LookRotation(-thisWayUp.normalized);
- fxSplashInstance.gameObject.layer = 0;
- Destroy(fxSplashInstance, 5f * this.rigidbody.mass);
- }
- Destroy(this.gameObject);
- }
- }
- if (oneExplosion == true)
- {
- septimer += Time.deltaTime;
- isSafe = false;
- if (soundDrop.audio.isPlaying == false && septimer < 2f && this.rigidbody.velocity.magnitude > 3f && !isTorpedo)
- {
- soundDrop.audio.Play();
- }
- if (soundDrop.audio.isPlaying == true && this.rigidbody.velocity.magnitude < 3f)
- {
- soundDrop.audio.Stop();
- }
- if (isRetarded)
- {
- if (retardDelay <= septimer)
- {
- if (this.rigidbody.drag != retardDrag)
- {
- this.rigidbody.drag = retardDrag;
- //print("Retarded Bomb Extended Brakes");
- }
- }
- }
- if (isClusterBomb && !isAirBurst)
- {
- if (isSafe == false && burstOnce == true)
- {
- timerGoBoom--;
- if (timerGoBoom <= 0f)
- {
- this.rigidbody.drag = (float)rndNumber.rndDouble(0.18, 0.5);
- int fragCache = clusterBomblets;
- GameObject[] exFrag = new GameObject[fragCache];
- for (int i = 0; i < exFrag.Length; i++)
- {
- exFrag[i] = GameDatabase.Instance.GetModel("IDSkillfulR1/Parts/IDWW1Bomb/model");
- exFrag[i].SetActive(true);
- exFrag[i].transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
- exFrag[i].transform.position = this.gameObject.transform.position + UnityEngine.Random.insideUnitSphere * (explosionPower * 0.225f);
- Vector3 randomDirection = new Vector3(rndNumber.rndRoll(-359, 359), rndNumber.rndRoll(-359, 359), rndNumber.rndRoll(-359, 359));
- exFrag[i].transform.Rotate(randomDirection);
- Rigidbody rb = exFrag[i].AddComponent<Rigidbody>();
- rb.detectCollisions = true;
- rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rb.mass = (this.rigidbody.mass / clusterBomblets);
- rb.drag = (float)rndNumber.rndDouble(0.001, 0.01);
- rb.velocity = this.rigidbody.velocity * 3f;
- setColliderStateInChildren(exFrag[i], true);
- fragImpact fI = exFrag[i].AddComponent<fragImpact>();
- fI.fragWarheadType = this.isWarheadType;
- fI.fragHardness = this.isHardness;
- Destroy(exFrag[i].gameObject, 300f);
- Destroy(this.gameObject);
- burstOnce = false;
- }
- }
- }
- }
- if (isAirBurst && !isClusterBomb)
- {
- if (partAltitude <= burstAlt && isSafe == false)
- {
- doExplosion();
- doShrapnel(this.gameObject, this.rigidbody.mass, this.rigidbody.velocity, this.explosionPower);
- //print("Airburst has Detonated!");
- }
- }
- if (isTorpedo)
- {
- if (torpedoLifeTimer > 0f)
- {
- if (septimer < 2f && waitPeriod == true)
- {
- headingT = holdTorpHeading.rotation;
- waitPeriod = false;
- }
- if (tGuided == true && waitPeriod == false)
- {
- this.gameObject.transform.rotation = headingT;
- }
- torpedoLifeTimer--;
- if(partAltitude < 0.0d)
- {
- this.rigidbody.AddForceAtPosition(this.gameObject.transform.forward * torpedoThrust, this.transform.position);
- }
- if (partAltitude < runDepth)
- {
- if (this.rigidbody.useGravity == true && zeroVelOnce == true)
- {
- this.rigidbody.velocity = Vector3.zero;
- zeroVelOnce = false;
- }
- this.rigidbody.useGravity = false;
- if (partAltitude < -1.85)
- {
- this.rigidbody.AddForceAtPosition(thisWayUp.normalized * 0.285f, this.transform.position);
- }
- }
- if (partAltitude > -0.625d)
- {
- this.rigidbody.useGravity = true;
- }
- if (torpedoLifeTimer <= 0f)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Torpedo ran out of fuel!", 4f, ScreenMessageStyle.UPPER_CENTER));
- Destroy(this.gameObject, 0.25f);
- }
- }
- }
- if (isRocket)
- {
- if (rocketSmokeFX == null && septimer < 2f)
- {
- try
- {
- rocketSmokeFX = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/rocketSmoke/model");
- }
- catch
- {
- print("Problem locating rocketSmoke");
- }
- if (rocketSmokeFX != null)
- {
- rocketSmokeFX.SetActive(true);
- rocketSmokeFX.transform.parent = this.gameObject.transform;
- if (thrustPoint != null)
- {
- rocketSmokeFX.transform.position = thrustPoint.position;
- }
- else
- {
- rocketSmokeFX.transform.position = this.transform.position;
- }
- rocketSmokeFX.gameObject.layer = 0;
- origTLT = torpedoLifeTimer;
- Destroy(rocketSmokeFX, torpedoLifeTimer * 0.05f);
- }
- }
- if (torpedoLifeTimer > 0f && partAltitude > 0.0)
- {
- torpedoLifeTimer--;
- if (septimer < (origTLT * 0.045f))
- {
- this.rigidbody.AddForceAtPosition(this.transform.forward * (torpedoThrust * rndNumber.rndFloat(0.85f, 1.0f)), this.transform.position);
- if (septimer < 2f && waitPeriod == true)
- {
- headingT = holdTorpHeading.rotation;
- this.gameObject.transform.rotation = headingT;
- }
- else if (septimer >= 2f && waitPeriod == true)
- {
- waitPeriod = false;
- }
- if (FlightGlobals.fetch.vesselTargetMode != FlightGlobals.VesselTargetModes.None && tGuided != false && waitPeriod == false)
- {
- ITargetable target = FlightGlobals.fetch.VesselTarget;
- Vector3 targetDirection = target.GetTransform().position - this.transform.position;
- Vector3 rotateTarget;
- if (targetDirection.sqrMagnitude > float.Epsilon)
- rotateTarget = targetDirection.normalized;
- else
- rotateTarget = transform.forward;
- var dot = Vector3.Dot(transform.forward, rotateTarget);
- if (1 - dot > float.Epsilon)
- {
- Vector3 rotationAxis;
- float angle;
- if (dot + 1 < float.Epsilon)
- {
- rotationAxis = Vector3.up;
- angle = Mathf.PI;
- }
- else
- {
- rotationAxis = Vector3.Cross(transform.forward, rotateTarget);
- angle = Mathf.Asin(Mathf.Min(1, rotationAxis.magnitude));
- rotationAxis.Normalize();
- if (dot < 0)
- angle = Mathf.PI - angle;
- }
- var desiredSpeed = Mathf.Sqrt(0.66f * angle * maxTorque / _inertia);
- var desiredVelocity = rotationAxis * desiredSpeed;
- var deltaVelocity = desiredVelocity - rigidbody.angularVelocity;
- if (deltaVelocity.sqrMagnitude > float.Epsilon)
- {
- var acceleration = deltaVelocity / Time.fixedDeltaTime;
- var torque = acceleration * _inertia;
- this.rigidbody.AddTorque(Vector3.ClampMagnitude(torque, maxTorque));
- }
- }
- }
- else
- {
- if (tGuided == true && waitPeriod == false)
- {
- this.gameObject.transform.rotation = headingT;
- this.rigidbody.useGravity = true;
- tGuided = false;
- }
- this.gameObject.transform.rotation = headingT;
- }
- }
- if (torpedoLifeTimer <= 0f || this.rigidbody.velocity.magnitude < 40f && septimer > 5f)
- {
- FXMonger.Explode(FlightGlobals.ActiveVessel.rootPart, this.transform.position, this.rigidbody.mass * 100f);
- Destroy(this.gameObject, 0.1f);
- }
- }
- }
- }
- }
- }
- public static void doShrapnel(GameObject thisBomb, float bombMass, Vector3 bombSpeed, float explodePower)
- {
- int shrapLimit = 10;
- #region Shrapnel Limit
- if (bombMass < 0.25f)
- {
- shrapLimit = 10;
- }
- if (bombMass >= 0.25f && bombMass < 0.5f)
- {
- shrapLimit = rndNumber.rndRoll(10, 20);
- }
- if (bombMass >= 0.5f && bombMass < 1f)
- {
- shrapLimit = rndNumber.rndRoll(15, 30);
- }
- if (bombMass >= 1f && bombMass < 4f)
- {
- shrapLimit = rndNumber.rndRoll(20, 40);
- }
- if (bombMass >= 4f && bombMass < 10f)
- {
- shrapLimit = rndNumber.rndRoll(30, 60);
- }
- #endregion
- int shrapnel = rndNumber.rndRoll(3, shrapLimit);
- int fragCache = shrapnel;
- GameObject[] exFrag = new GameObject[fragCache];
- for (int i = 0; i < exFrag.Length; i++)
- {
- exFrag[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
- exFrag[i].SetActive(true);
- exFrag[i].renderer.enabled = false;
- exFrag[i].transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
- exFrag[i].transform.position = thisBomb.transform.position;
- exFrag[i].transform.rotation = UnityEngine.Random.rotationUniform;
- Rigidbody rb = exFrag[i].AddComponent<Rigidbody>();
- setColliderStateInChildren(exFrag[i], true);
- rb.detectCollisions = true;
- rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rb.mass = (bombMass / shrapnel);
- rb.drag = rndNumber.rndFloat(0.1f, 0.25f);
- fragImpact fI = exFrag[i].AddComponent<fragImpact>();
- fI.fragWarheadType = 0f;
- fI.fragHardness = 320f;
- rb.velocity = exFrag[i].transform.forward * (explodePower * (rndNumber.rndFloat(0.5f, 1.5f)));
- Destroy(exFrag[i].gameObject, 3f);
- }
- }
- public static void setColliderStateInChildren(GameObject rootObject, bool isTrigger)
- {
- Collider[] colliders = rootObject.GetComponentsInChildren<Collider>(true);
- for (int i = 0; i < colliders.Length; i++)
- {
- colliders[i].isTrigger = isTrigger;
- colliders[i].enabled = true;
- }
- }
- private void doExplosion()
- {
- oneExplosion = false;
- GameObject explosion = Part.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustSparks_yellow")) as GameObject;
- explosion.transform.localEulerAngles = Vector3.zero;
- explosion.transform.localPosition = new Vector3(0, 0, 0);
- explosion.transform.position = this.transform.position;
- ParticleEmitter emitter = explosion.particleEmitter;
- emitter.emit = false;
- emitter.minSize = 5f;
- emitter.maxSize = blastRadius * 0.2f;
- emitter.minEnergy = 4f;
- emitter.maxEnergy = 6f;
- emitter.minEmission = 14f;
- emitter.maxEmission = 20f;
- emitter.rndVelocity = Vector3.one * 0.01f;
- emitter.localVelocity = Vector3.zero;
- emitter.useWorldSpace = true;
- emitter.renderer.castShadows = true;
- emitter.renderer.receiveShadows = true;
- ParticleAnimator emitterAnimator = emitter.GetComponent<ParticleAnimator>();
- emitterAnimator.sizeGrow = -0.75f;
- emitterAnimator.particleEmitter.maxSize = 0.45f;
- Color[] emitterColors = emitterAnimator.colorAnimation;
- emitterColors[0] = new Color(1f, 1f, 1f, 0.82f);
- emitterColors[1] = new Color(1f, 0.25f, 0.25f, 0.37f);
- emitterColors[2] = new Color(0.25f, 0.3f, 0f, 0.5f);
- emitterColors[3] = new Color(0.9f, 0.9f, 0.9f, 0.66f);
- emitterColors[4] = new Color(1f, 1f, 1f, 0.05f);
- emitterAnimator.colorAnimation = emitterColors;
- emitter.Emit(30);
- FXMonger.Explode(FlightGlobals.ActiveVessel.rootPart, this.transform.position, 0.9f);
- //print("Bomb has detonated with a force of " + explosionPower);
- }
- public void OnTriggerEnter(Collider Collision)
- {
- if (Collision.gameObject.layer == 15)
- {
- //print("hit the ground or a building, warhead is: " + isWarheadType);
- if (isWarheadType == 1f || isWarheadType == 2f)
- {
- FXMonger.Explode(FlightGlobals.ActiveVessel.rootPart, this.transform.position, this.rigidbody.mass);
- }
- if (isWarheadType == 2f)
- {
- //print("this is an Incendiary hit!");
- GameObject fxFireInstance = new GameObject();
- try
- {
- fxFireInstance = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/largeGFire/model");
- }
- catch
- {
- print("Problem locating fireFX");
- }
- if (fxFireInstance != null)
- {
- float fireTemp = 100f;
- //print("Setting fx active");
- fxFireInstance.SetActive(true);
- fxFireInstance.transform.parent = null;
- fxFireInstance.transform.position = this.transform.position;
- fxFireInstance.gameObject.layer = 0;
- if (isRocket)
- {
- fireTemp = 50f;
- }
- terrainBurner tB = fxFireInstance.AddComponent<terrainBurner>();
- tB.throwsHeat = fireTemp;
- tB.heatRange = this.rigidbody.mass * 30f;
- Destroy(fxFireInstance, 300f * (float)rndNumber.rndDouble(0.75, 2.5));
- }
- }
- terrainHit();
- }
- }
- public void terrainHit()
- {
- GameObject explosion = Part.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustSparks_yellow")) as GameObject;
- explosion.transform.localEulerAngles = Vector3.zero;
- explosion.transform.localPosition = new Vector3(0, 0, 0);
- explosion.transform.position = this.transform.position;
- ParticleEmitter emitter = explosion.particleEmitter;
- emitter.emit = false;
- emitter.minSize = (this.rigidbody.mass * 0.5f) + 0.35f;
- emitter.maxSize = (this.rigidbody.mass * 2f) + 1f;
- emitter.minEnergy = (this.rigidbody.mass * (this.rigidbody.velocity.magnitude * 0.01f)) + 1.2f;
- emitter.maxEnergy = (this.rigidbody.mass * (this.rigidbody.velocity.magnitude * 0.01f)) + 1.5f;
- emitter.rndVelocity = Vector3.one * (float)rndNumber.rndDouble(0.01, 1.0);
- emitter.localVelocity = Vector3.zero;
- emitter.useWorldSpace = true;
- ParticleAnimator emitterAnimator = emitter.GetComponent<ParticleAnimator>();
- emitterAnimator.sizeGrow = 0.0045f;
- Color[] emitterColors = emitterAnimator.colorAnimation;
- emitterColors[0] = new Color(0.5f, 0.45f, 0.18f, 0.95f);
- emitterColors[1] = new Color(0.8f, 0.8f, 0.8f, 1f);
- emitterColors[2] = new Color(0.85f, 0.1f, 0.1f, 0.7f);
- emitterColors[3] = new Color(0.5f, 0.5f, 0.5f, 0.5f);
- emitterColors[4] = new Color(0f, 0f, 0f, 0.25f);
- emitterAnimator.colorAnimation = emitterColors;
- emitter.Emit(8);
- if (!isClusterBomb && isWarheadType == 1f)
- {
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- float blastDistance = Vector3.Distance(v.transform.position, this.transform.position);
- if (blastDistance < blastRadius)
- {
- try
- {
- v.GoOffRails();
- }
- catch
- {
- print("Something is wrong with making the vessel offrails");
- }
- FXMonger.Explode(v.rootPart, v.transform.position, 0.9f / blastDistance);
- v.rigidbody.AddForceAtPosition(Vector3.forward * (explosionPower / (blastDistance * 0.25f)), v.transform.position, ForceMode.Impulse);
- }
- }
- doShrapnel(this.gameObject, this.rigidbody.mass, this.rigidbody.velocity, explosionPower);
- }
- Destroy(this.gameObject);
- }
- }
- public class rndNumber
- {
- public static System.Random rnd = new System.Random();
- public static int rndRoll(int min, int max)
- {
- return rnd.Next(min, max);
- }
- public static System.Random rnd2 = new System.Random();
- public static double rndDouble(double min, double max)
- {
- return rnd2.NextDouble();
- }
- public static System.Random rnd3 = new System.Random();
- public static float rndFloat(float min, float max)
- {
- return (float)rnd3.NextDouble();
- }
- }
- public class terrainBurner : MonoBehaviour
- {
- public float throwsHeat = 100f;
- public float heatRange = 30f;
- public void FixedUpdate()
- {
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- if (v.isEVA == false)
- {
- foreach (Part p in v.Parts)
- {
- float blastDistance = Vector3.Distance(p.transform.position, this.transform.position);
- if (blastDistance < 1f)
- {
- blastDistance = 1f;
- }
- if (blastDistance < heatRange)
- {
- p.temperature += (throwsHeat * (heatRange / blastDistance)) * Time.deltaTime;
- }
- }
- }
- }
- }
- }
- public class fragImpact : MonoBehaviour
- {
- public double partAltitude;
- public float fragHardness = 250f;
- public float fragWarheadType = 1f;
- public void FixedUpdate()
- {
- partAltitude = Vector3.Distance(this.rigidbody.transform.position, FlightGlobals.ActiveVessel.mainBody.position) - (float)FlightGlobals.ActiveVessel.mainBody.Radius;
- if (this.partAltitude < -3.0)
- {
- FXMonger.Splash(this.transform.position, this.rigidbody.velocity.magnitude * this.rigidbody.mass);
- terrainHit();
- }
- }
- public void OnTriggerEnter(Collider Collision)
- {
- if (Collision.gameObject.layer == 15)
- {
- if (fragWarheadType == 1f) FXMonger.Explode(FlightGlobals.ActiveVessel.rootPart, this.transform.position, this.rigidbody.mass);
- terrainHit();
- }
- }
- public void terrainHit()
- {
- GameObject explosion = Part.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustSparks_yellow")) as GameObject;
- explosion.transform.localEulerAngles = Vector3.zero;
- explosion.transform.localPosition = new Vector3(0, 0, 0);
- explosion.transform.position = this.transform.position;
- ParticleEmitter emitter = explosion.particleEmitter;
- emitter.emit = false;
- emitter.minSize = (this.rigidbody.mass * 0.5f) + 0.35f;
- emitter.maxSize = (this.rigidbody.mass * 2f) + 1f;
- emitter.minEnergy = (this.rigidbody.mass * (this.rigidbody.velocity.magnitude * 0.01f)) + 1.2f;
- emitter.maxEnergy = (this.rigidbody.mass * (this.rigidbody.velocity.magnitude * 0.01f)) + 1.5f;
- emitter.rndVelocity = Vector3.one * (float)rndNumber.rndDouble(0.01, 1.0);
- emitter.localVelocity = Vector3.zero;
- emitter.useWorldSpace = true;
- ParticleAnimator emitterAnimator = emitter.GetComponent<ParticleAnimator>();
- emitterAnimator.sizeGrow = 0.0045f;
- Color[] emitterColors = emitterAnimator.colorAnimation;
- emitterColors[0] = new Color(0.5f, 0.45f, 0.18f, 0.95f);
- emitterColors[1] = new Color(0.8f, 0.8f, 0.8f, 1f);
- emitterColors[2] = new Color(0.85f, 0.1f, 0.1f, 0.7f);
- emitterColors[3] = new Color(0.5f, 0.5f, 0.5f, 0.5f);
- emitterColors[4] = new Color(0f, 0f, 0f, 0.25f);
- emitterAnimator.colorAnimation = emitterColors;
- emitter.Emit(8);
- Destroy(this.gameObject);
- }
- }
- ************************************************************************ordnancepart
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- using System.Linq;
- public class targetPart : PartModule
- {
- [KSPField(isPersistant = true)]
- public float targetStructure = 0f;
- [KSPField]
- public float targetHardness = 150f;
- [KSPField]
- public float targetNotVoid = 1f;
- [KSPField]
- public float targetType = 2f;
- [KSPField(guiActive = true, guiName = "Current Structure", isPersistant = true)]
- public float currentPartStructure;
- [KSPField(guiActive = true, guiName = "Current Temperature", isPersistant = false)]
- public float currentPartTemp;
- [KSPField]
- public string objectType = "none";
- public float heatProduction = 1050f;
- [KSPField(isPersistant = true)]
- public float currentMass;
- [KSPField(isPersistant = true)]
- private float originalMass;
- [KSPField(isPersistant = true)]
- private bool hasBeenHit = false;
- [KSPField(isPersistant = true)]
- public bool torpWaterlinePenetration = false;
- [KSPField(isPersistant = true)]
- public bool isSinking = false;
- [KSPField(isPersistant = true)]
- public float vesselOriginalTotalMass;
- [KSPField(isPersistant = true)]
- public float targetPartVolume = 0f;
- [KSPField(isPersistant = true)]
- public bool targetBurnedOut;
- [KSPField(isPersistant = true)]
- public float countedTargetParts;
- [KSPField(isPersistant = true)]
- public float checkCritSink;
- [KSPField(guiActive = true, guiName = "Part Burning", isPersistant = true)]
- public bool targetIsBurning = false;
- [KSPField(isPersistant = true)]
- public bool weKnowOrigMass = false;
- public float explosionPower;
- public bool bombJustExploded = false;
- private float structHitLoss;
- public int fireFlicker;
- public float timeFireFlicker;
- public float fireSpreadModifier = 2.5f;
- public GameObject fxFireInstance;
- public Vector3 thisWayUp;
- //*************************************
- public float projPenBaseline = 1f;
- public float projPenetrate = 0f;
- public float projHardness;
- public float impactEnergy;
- public float penetrateChance;
- public float projectileMass;
- public float projectileVelocity;
- public bool fuelLeak = false;
- public double fLeakRate = 0.0;
- public double leakToLevel = 1.0;
- [KSPField(isPersistant = true)]
- public float wingOriginalSurfaceArea;
- public float dmgCalcScaler = 1f;
- //***********************************************
- private List<targetPart> targList;
- private List<targetPart> countList;
- public bool thisPartRestored = false;
- //**********************************************
- private List<targetPart> sinkList;
- public int targToSinkNumber;
- public bool setConditionS = false;
- public float sinkCheckTime;
- public float countSTimer;
- public float sinkStartTime;
- //*******************
- public bool setConditionF = false;
- public float fireDieTimer = 120f;
- public float fireStartTimer = 30f;
- public float fireTicker = 0f;
- //************************************************************************************
- [KSPField(guiActive = false, guiName = "Part Volume", isPersistant = true)]
- public float thisPartMeshVolume;
- public float SignedVolumeOfTriangle(Vector3 p1, Vector3 p2, Vector3 p3)
- {
- float v321 = p3.x * p2.y * p1.z;
- float v231 = p2.x * p3.y * p1.z;
- float v312 = p3.x * p1.y * p2.z;
- float v132 = p1.x * p3.y * p2.z;
- float v213 = p2.x * p1.y * p3.z;
- float v123 = p1.x * p2.y * p3.z;
- return (1.0f / 6.0f) * (-v321 + v231 + v312 - v132 - v213 + v123);
- }
- float VolumeOfMesh(Mesh mesh)
- {
- float volume = 0;
- Vector3[] vertices = mesh.vertices;
- int[] triangles = mesh.triangles;
- for (int i = 0; i < mesh.triangles.Length; i += 3)
- {
- Vector3 p1 = vertices[triangles[i + 0]];
- Vector3 p2 = vertices[triangles[i + 1]];
- Vector3 p3 = vertices[triangles[i + 2]];
- volume += SignedVolumeOfTriangle(p1, p2, p3);
- }
- return Mathf.Abs(volume);
- }
- //***************************************
- public float warheadModifier = 0;
- public bool wasHitByIncindiary = false;
- public bool hitIsTorpedo = false;
- //**************************************
- public GameObject bulletHoleInstance;
- public float vesselMass = 0f;
- public AudioSource bulletHitM1, bulletHitM2;
- public fragImpact fragImpactHandler;
- public bool kerbalFightsFire = false;
- //*******************************
- public Rigidbody thisBRB;
- public Vector3 thisTargetPOS;
- public Transform foundDmgState;
- public string useFireFX = "IDSkillfulR1/Effects/smallFire/model";
- public bool firstRun = true;
- #region fix variables
- public bool fixOngoing = false;
- public string jobName = "nil";
- public float fixTime = 0f;
- public float startTime = 0f;
- public bool takeResOnce = false;
- public float doneTime = 0f;
- public float ourKerbalsStupid = 0f;
- public float ourKerbalCourage = 0f;
- public bool ourKerbalIsBadass = false;
- public string lastKerbalName = "";
- #endregion
- public bool setCSinCNew = false;
- [KSPEvent(active = true, guiName = "Fight Fire", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 8f)]
- public void fixFire()
- {
- bool allowFireFight = false;
- foreach (Part p in this.vessel.Parts)
- {
- targetPart tP = p.GetComponent<targetPart>();
- if (tP != null && tP.targetIsBurning == true)
- {
- allowFireFight = true;
- }
- }
- if (kerbalFightsFire == false && allowFireFight == true)
- {
- kerbalFightsFire = true;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Kerbal fighting any fires! ...moving will abort job!...", 5f, ScreenMessageStyle.UPPER_CENTER));
- }
- else
- {
- kerbalFightsFire = false;
- }
- }
- [KSPEvent(active = true, guiName = "Fix Damage", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void fixState()
- {
- bool allowJob = false;
- foreach (Part p in this.vessel.Parts)
- {
- relayIFF rI = p.GetComponent<relayIFF>();
- if (rI != null)
- {
- allowJob = true;
- }
- }
- if (fixOngoing == false && allowJob == true)
- {
- jobName = "Fix";
- fixTime = 60f * (1f + ourKerbalsStupid);
- startTime = Time.time;
- //print(startTime + " is the time the job started. ET to complete: " + fixTime);
- ScreenMessages.PostScreenMessage(new ScreenMessage("This might take a while! Please be patient! ...and quiet!...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- takeResOnce = true;
- doneTime = fixTime + startTime;
- }
- }
- public void Start()
- {
- try
- {
- foundDmgState = this.part.FindModelTransform("dmgState");
- }
- catch
- {
- print("Part has no Damage Model - no swap will happen");
- }
- if (foundDmgState != null)
- {
- if (currentPartStructure > 0f)
- {
- Transform affectDmgState = this.part.FindModelTransform("dmgState");
- affectDmgState.GetComponent<MeshRenderer>().enabled = false;
- Transform affectCleanState = this.part.FindModelTransform("targetPart");
- affectCleanState.GetComponent<MeshRenderer>().enabled = true;
- }
- if (currentPartStructure == 0f)
- {
- Transform affectDmgState = this.part.FindModelTransform("dmgState");
- affectDmgState.GetComponent<MeshRenderer>().enabled = true;
- Transform affectCleanState = this.part.FindModelTransform("targetPart");
- affectCleanState.GetComponent<MeshRenderer>().enabled = false;
- }
- if (!HighLogic.LoadedSceneIsFlight)
- {
- Transform affectDmgState = this.part.FindModelTransform("dmgState");
- affectDmgState.GetComponent<MeshRenderer>().enabled = false;
- Transform affectCleanState = this.part.FindModelTransform("targetPart");
- affectCleanState.GetComponent<MeshRenderer>().enabled = true;
- }
- }
- #region Bullet Hit Sounds
- if (!GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/IDhitM1") || !GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/IDhitM2")) return;
- bulletHitM1 = this.gameObject.AddComponent<AudioSource>();
- bulletHitM2 = this.gameObject.AddComponent<AudioSource>();
- bulletHitM1.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDhitM1");
- bulletHitM2.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDhitM2");
- if (bulletHitM1 != null)
- {
- bulletHitM1.audio.volume = GameSettings.SHIP_VOLUME;
- bulletHitM1.audio.rolloffMode = AudioRolloffMode.Linear;
- bulletHitM1.audio.dopplerLevel = 0f;
- bulletHitM1.audio.panLevel = 1f;
- bulletHitM1.audio.loop = false;
- bulletHitM1.audio.playOnAwake = false;
- bulletHitM1.audio.priority = 3;
- }
- if (bulletHitM2 != null)
- {
- bulletHitM2.audio.volume = GameSettings.SHIP_VOLUME;
- bulletHitM2.audio.rolloffMode = AudioRolloffMode.Linear;
- bulletHitM2.audio.dopplerLevel = 0f;
- bulletHitM2.audio.panLevel = 1f;
- bulletHitM2.audio.loop = false;
- bulletHitM2.audio.playOnAwake = false;
- bulletHitM2.audio.priority = 3;
- }
- #endregion
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (FlightGlobals.ActiveVessel.isEVA == true)
- {
- if (this.vessel.horizontalSrfSpeed > 0.2f)
- {
- kerbalFightsFire = false;
- }
- relayIFF rI = this.GetComponent<relayIFF>();
- if (rI != null)
- {
- ProtoCrewMember getStats = FlightGlobals.ActiveVessel.GetVesselCrew().FirstOrDefault();
- if (lastKerbalName != getStats.name)
- {
- checkKerbal();
- }
- }
- }
- if (fixOngoing == true && doneTime > Time.time && (this.part.transform.position.magnitude - FlightGlobals.ActiveVessel.transform.position.magnitude) > 4f || fixOngoing == true && doneTime > Time.time && FlightGlobals.ActiveVessel.isEVA == false)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("You botched the job! Please stay within 4m of the job site, do not switch away or enter any vessel.", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- }
- if (fixOngoing == true && doneTime < Time.time && jobName == "Fix")
- {
- //print("Inside the condition...");
- bool foundParts = false;
- List<Collider> nearestColliders = new List<Collider>(Physics.OverlapSphere(this.transform.position, 40f));
- foreach (Collider col in nearestColliders)
- {
- if (!col.attachedRigidbody)
- {
- continue;
- }
- Part p = col.attachedRigidbody.GetComponent<Part>();
- if (!p)
- {
- continue;
- }
- PartResourceList resourceList = p.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "SpareParts")
- {
- //print("Found a part with SpareParts!");
- if (resource.amount < 0.25)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("We ran out of SpareParts, can't finish this job!", 3f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- takeResOnce = false;
- }
- else if (resource.amount >= 0.25)
- {
- if (takeResOnce == true)
- {
- resource.amount = resource.amount - 0.25;
- //print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- ScreenMessages.PostScreenMessage(new ScreenMessage("This Vessel is restored!", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- takeResOnce = false;
- foundParts = true;
- foreach (Part pToFix in this.vessel.parts)
- {
- targetPart t = pToFix.GetComponent<targetPart>();
- t.currentPartStructure = t.targetStructure;
- t.setCSinCNew = true;
- t.part.SetHighlightColor(Color.clear);
- t.part.SetHighlight(true);
- t.part.gameObject.SendMessage("ApplyDamage", 1f);
- t.hasBeenHit = false;
- t.isSinking = false;
- t.targetIsBurning = false;
- t.targetBurnedOut = false;
- t.torpWaterlinePenetration = false;
- t.wasHitByIncindiary = false;
- enablePartFunctions();
- }
- }
- }
- }
- }
- }
- if (foundParts != true)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("I pulled this all apart for nothing. Without spare parts we can't fix this!", 3f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- takeResOnce = false;
- }
- }
- }
- if (HighLogic.LoadedSceneIsFlight && !this.vessel.isEVA)
- {
- thisWayUp = (this.vessel.transform.position - this.vessel.mainBody.position).normalized;
- if (firstRun == true)
- {
- vesselMass = this.vessel.GetTotalMass();
- checkMeshVolume();
- targList = new List<targetPart>();
- sinkList = new List<targetPart>();
- countList = new List<targetPart>();
- if (objectType == "targetObj" && hasBeenHit == false && weKnowOrigMass == false)
- {
- originalMass = (part.GetResourceMass() + part.mass);
- currentMass = originalMass;
- if (targetPartVolume == 0)
- {
- targetPartVolume = thisPartMeshVolume;
- }
- if (targetStructure == 0f)
- {
- targetStructure = ((targetPartVolume * targetHardness) * targetNotVoid) / 20f;
- if (targetStructure < 1f && targetStructure > 0f) targetStructure = 1f;
- }
- currentPartStructure = targetStructure;
- currentPartTemp = part.temperature;
- try
- {
- foundDmgState = this.part.FindModelTransform("dmgState");
- }
- catch
- {
- print("Part has no Damage Model - no swap will happen");
- }
- if (foundDmgState != null)
- {
- Transform affectDmgState = this.part.FindModelTransform("dmgState");
- affectDmgState.GetComponent<MeshRenderer>().enabled = false;
- Transform affectCleanState = this.part.FindModelTransform("targetPart");
- affectCleanState.GetComponent<MeshRenderer>().enabled = true;
- }
- }
- else if (objectType == "targetObj" && weKnowOrigMass == true)
- {
- this.part.mass = currentMass;
- }
- firstRun = false;
- }
- if (this.part.vessel.loaded)
- {
- if (this.currentPartStructure == -123f && thisPartRestored == true)
- {
- disablePartFunctions();
- this.part.SetHighlightColor(Color.yellow);
- this.part.SetHighlight(true);
- //print("Past the condition, check for yellow");
- thisPartRestored = false;
- }
- if (setCSinCNew == true)
- {
- setColliderStateInChildren(this.gameObject, 0);
- setCSinCNew = false;
- }
- thisTargetPOS = this.part.transform.position;
- warheadModifier = 0;
- if (vessel.GetTotalMass() != 0 && weKnowOrigMass == false)
- {
- vesselOriginalTotalMass = vessel.GetTotalMass();
- weKnowOrigMass = true;
- #region CountTargetFloatingHullParts
- foreach (Part p in vessel.parts)
- {
- PartModule m = p.GetComponent<PartModule>();
- if (m is targetPart)
- {
- targetPart countParts = m.GetComponent<targetPart>();
- if (countParts != null && countParts.isSinking == false && countParts.targetType == 1) // Look for all floating hull parts.
- {
- //print("past the conditions");
- countList.Add(countParts);
- if (countList.Count > 0)
- {
- countedTargetParts = countList.Count; //just floating hull parts!!!
- }
- }
- }
- }
- #endregion
- checkCritSink = countedTargetParts * targetPartVolume;
- }
- if (currentPartStructure < targetStructure && part.WaterContact == true || torpWaterlinePenetration == true && part.WaterContact == true)
- {
- isSinking = true;
- if(vessel.altitude < -10.0) targetIsBurning = false;
- if (vessel.altitude < -300.0)
- {
- //print("Ship is sunk, get rid of it!");
- foreach (Part p in vessel.Parts)
- {
- FXMonger.Explode(this.part, this.part.transform.position, 1f);
- p.explode();
- }
- }
- }
- else
- {
- isSinking = false;
- sinkStartTime = 0;
- countSTimer = 0;
- }
- if (this.part.temperature > (this.part.maxTemp * 0.8f))
- {
- this.targetIsBurning = true;
- }
- if (targetBurnedOut == true)
- {
- float coolDown = FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody);
- this.part.temperature = Mathf.Lerp(this.part.temperature, coolDown, 1f);
- }
- if (targetIsBurning == true && part.vessel.atmDensity > 0.3 && targetBurnedOut == false)
- {
- part.temperature += (heatProduction * (float)rndNumber.rndDouble(0.85, 1.25)) * TimeWarp.deltaTime;
- currentPartTemp = part.temperature;
- if (this.part.temperature > this.part.maxTemp * 0.1f && this.targetStructure > 1.5f)
- {
- if (fxFireInstance == null || fxFireInstance.activeInHierarchy == false)
- {
- setFireFX();
- try
- {
- fxFireInstance = GameDatabase.Instance.GetModel(useFireFX);
- }
- catch
- {
- print("Problem locating fireFX");
- }
- if (fxFireInstance != null)
- {
- //print("ordinanceInstance is not null!");
- fxFireInstance.SetActive(true);
- fxFireInstance.transform.position = this.part.transform.position;
- fxFireInstance.transform.parent = this.part.transform;
- fxFireInstance.gameObject.layer = 0;
- }
- }
- if (fireDieTimer > 0f)
- {
- fireDieTimer--;
- if (fireDieTimer <= 0f)
- {
- float fireFighter = 0f;
- fireTicker++;
- float fireDiesChance = 5f;
- if (wasHitByIncindiary == true) fireDiesChance *= 0.7f;
- if (fuelLeak == true) fireDiesChance *= 0.15f;
- if (kerbalFightsFire == true)
- {
- fireFighter = 5f;
- }
- fireDiesChance *= ((fireTicker * 0.025f) * fireFighter);
- float randomNumber = (float)rndNumber.rndRoll(1, 100);
- if (randomNumber < fireDiesChance)
- {
- targetIsBurning = false;
- fireTicker = 0f;
- float coolDown = FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody);
- this.part.temperature = Mathf.Lerp(this.part.temperature, coolDown, 1f);
- hasBeenHit = false;
- fxFireInstance.SetActive(false);
- }
- fireDieTimer = 110f;
- }
- }
- if (this.part.temperature > this.part.maxTemp * 0.6f)
- {
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel" || resource.resourceName == "HEcharge" || resource.resourceName == "SolidFuel")
- {
- float chanceToBlow = this.part.temperature * 0.0005f;
- float rollTheDice = (float)rndNumber.rndRoll(1, 200);
- if (rollTheDice < chanceToBlow)
- {
- FXMonger.Explode(this.part, this.part.transform.position, ((float)resource.amount * 0.125f));
- this.targetBurnedOut = true;
- print("Fuel Explosion, fire is out!");
- fxFireInstance = null;
- targetIsBurning = false;
- currentPartStructure = -1f;
- doTheDamage();
- targList.Clear();
- if (rollTheDice < (chanceToBlow * 0.5f))
- {
- this.part.explode();
- }
- }
- }
- }
- }
- if (this.part.temperature > this.part.maxTemp * 0.9f)
- {
- targetBurnedOut = true;
- print("Part Burned Out!");
- fxFireInstance = null;
- targetIsBurning = false;
- currentPartStructure = -1f;
- bombJustExploded = true;
- doTheDamage();
- targList.Clear();
- }
- }
- }
- if (targetIsBurning == false && targetBurnedOut == false || part.vessel.atmDensity > 0.3)
- {
- targetIsBurning = false;
- currentPartTemp = part.temperature;
- targList.Clear();
- }
- if (fuelLeak == true)
- {
- checkFuelLoss();
- }
- #region FIRE START CODE ^^^^^^^^^^^^~^~^~^~^~^~^~^~^~^~^~^^^^^^^^^^^^^^
- if (currentPartStructure < targetStructure && hasBeenHit == true || fuelLeak == true)
- {
- if (part.vessel.atmDensity > 0.3 && targetIsBurning == false && isSinking == false && targetBurnedOut == false)
- {
- if (fireStartTimer > 0f)
- {
- fireStartTimer--;
- if (fireStartTimer <= 0f)
- {
- float chanceOfFire = rndNumber.rndFloat(0.35f, 1.1f);
- if (warheadModifier == 1f) chanceOfFire *= 1.2f;
- if (wasHitByIncindiary == true) chanceOfFire *= 1.4f;
- if (fuelLeak == true) chanceOfFire *= 1.4f;
- //print(chanceOfFire + " %");
- float randomNumber = rndNumber.rndFloat(1f, 100f);
- if (randomNumber < chanceOfFire)
- {
- targetIsBurning = true;
- }
- fireStartTimer = 30f;
- }
- }
- }
- }
- #endregion
- }
- }
- }
- private void checkPenetrate()
- {
- if (warheadModifier == 3f) projHardness = (projHardness * 1.75f);
- if (warheadModifier == 2f) projHardness = (projHardness * 0.75f);
- float adjustVelocityChance = projectileVelocity;
- if (adjustVelocityChance < 0f) adjustVelocityChance = 1f;
- if (projHardness > this.targetHardness)
- {
- projPenBaseline = 50f;
- }
- else projPenBaseline = 0f;
- penetrateChance = ((((projHardness / this.targetHardness) * projPenetrate) + projPenBaseline) * (adjustVelocityChance / 300f) / (this.currentPartStructure/5f)) + (projectileMass * 95f);
- if (penetrateChance <= 1f) penetrateChance = 1f;
- if (penetrateChance > 99f) penetrateChance = 99f;
- float penRoll = rndNumber.rndRoll(0, 100);
- if (penRoll < penetrateChance)
- {
- //print("PENETRATION! : penchance was " + penetrateChance + "Penetrate roll was " + penRoll);
- bombJustExploded = true;
- doTheDamage();
- fLeakRate = (double)projPenetrate * 0.033;
- }
- else
- {
- //print("NO PENETRATION : penchance was " + penetrateChance + "Penetrate roll was " + penRoll);
- }
- if (!bulletHitM1.audio.isPlaying)
- {
- bulletHitM1.audio.Play();
- }
- else
- {
- bulletHitM2.audio.Play();
- }
- this.rigidbody.AddForceAtPosition(Vector3.forward * ((projectileVelocity * projectileMass * projHardness) / (vesselMass * 150f)), this.transform.position, ForceMode.Impulse);
- }
- private void doTheDamage()
- {
- bool avoidDamage = false;
- relayIFF isIFF = base.part.GetComponent<relayIFF>();
- if (isIFF == null)
- {
- isIFF = base.part.GetComponentsInChildren<relayIFF>().FirstOrDefault();
- }
- if (isIFF != null)
- {
- avoidDamage = true;
- }
- if (bombJustExploded == true && avoidDamage == false)
- {
- float isHEModifier = 1f;
- if (warheadModifier == 1f) isHEModifier = 2.5f;
- if (warheadModifier == 2f) wasHitByIncindiary = true;
- if (hitIsTorpedo == true)
- {
- isHEModifier = 10f;
- torpWaterlinePenetration = true;
- }
- float randomDamageMod = ((float)rndNumber.rndDouble(0.01, 1.0) + 0.75f);
- isHEModifier = isHEModifier * randomDamageMod;
- structHitLoss = ((projectileMass * projectileVelocity) * (projHardness / targetHardness)) * isHEModifier;
- currentPartStructure = currentPartStructure - structHitLoss;
- print("Impact Vel: " + projectileVelocity + "after suffering " + structHitLoss + " damage, Structure is now " + currentPartStructure);
- float perDamaged = (currentPartStructure / targetStructure);
- if (perDamaged < 0.01f) perDamaged = 0.01f;
- this.part.gameObject.SendMessage("ApplyDamage", perDamaged);
- if (currentPartStructure < 0f)
- {
- float determineFate = rndNumber.rndRoll(1, 100);
- float fateCheckValue = 5f;
- if ((targetStructure * 0.25f) < (projPenetrate * 0.5f)) fateCheckValue = 7.5f;
- if ((targetStructure * 0.5f) < (projPenetrate * 0.5f)) fateCheckValue = 12.5f;
- if ((targetStructure * 0.75f) < (projPenetrate * 0.5f)) fateCheckValue = 25f;
- if (targetStructure < (projPenetrate * 0.5f)) fateCheckValue = 50f;
- if ((float)determineFate <= fateCheckValue)
- {
- //print("This target part is totally destroyed!");
- if (this.part.mass > 3.5f)
- {
- doIDExplode();
- }
- this.part.explode();
- }
- else if ((float)determineFate > fateCheckValue)
- {
- //print("This target part is destroyed! repair it later!");
- currentPartStructure = 0f;
- this.part.SetHighlightColor(Color.yellow);
- this.part.SetHighlight(true);
- this.part.gameObject.SendMessage("ApplyDamage", 0.01f);
- setColliderStateInChildren(this.gameObject, 1);
- if (foundDmgState != null)
- {
- //print("Changing to the damage model");
- Transform affectDmgState = this.part.FindModelTransform("dmgState");
- affectDmgState.GetComponent<MeshRenderer>().enabled = true;
- Transform affectCleanState = this.part.FindModelTransform("targetPart");
- affectCleanState.GetComponent<MeshRenderer>().enabled = false;
- }
- disablePartFunctions();
- }
- if (isSinking == true)
- {
- targetIsBurning = false;
- }
- }
- hasBeenHit = true;
- bombJustExploded = false;
- }
- }
- public static void setColliderStateInChildren(GameObject rootObject, int layerInt)
- {
- Collider[] colliders = rootObject.GetComponentsInChildren<Collider>(true);
- for (int i = 0; i < colliders.Length; i++)
- {
- colliders[i].gameObject.layer = layerInt;
- }
- }
- public void disablePartFunctions()
- {
- if(this.currentPartStructure <= 0f)
- {
- if (this.gameObject.GetComponentInChildren<ModuleEngines>() == true)
- {
- ModuleEngines thisTargetEngine = this.gameObject.GetComponentInChildren<ModuleEngines>();
- thisTargetEngine.allowRestart = false;
- thisTargetEngine.Shutdown();
- thisTargetEngine.DeactivateRunningFX();
- thisTargetEngine.DeactivatePowerFX();
- thisTargetEngine.enabled = false;
- }
- if (this.gameObject.GetComponentInChildren<ModuleEnginesFX>() == true)
- {
- ModuleEnginesFX thisTargetEngine = this.gameObject.GetComponentInChildren<ModuleEnginesFX>();
- thisTargetEngine.allowRestart = false;
- thisTargetEngine.Shutdown();
- thisTargetEngine.DeactivateLoopingFX();
- thisTargetEngine.isEnabled = false;
- }
- if (this.gameObject.GetComponentInChildren<IDDepot>() == true)
- {
- float chanceToBlow = (float)rndNumber.rndDouble(0.01, 75.0) * projPenetrate;
- float makeBlowRoll = rndNumber.rndRoll(0, 100);
- if (chanceToBlow > makeBlowRoll)
- {
- doIDExplode();
- FXMonger.Explode(this.part, this.part.transform.position, this.currentMass);
- this.part.explode();
- }
- }
- if (this.gameObject.GetComponentInChildren<ControlSurface>() == true)
- {
- ControlSurface thisTargetSurface = this.gameObject.GetComponentInChildren<ControlSurface>();
- wingOriginalSurfaceArea = thisTargetSurface.deflectionLiftCoeff;
- thisTargetSurface.ctrlSurfaceRange = rndNumber.rndRoll(0, 20);
- thisTargetSurface.deflectionLiftCoeff = wingOriginalSurfaceArea * (float)rndNumber.rndDouble(0.01, 0.95);
- print("Wing has taken damage");
- }
- if (this.gameObject.GetComponentInChildren<FuelLine>() == true)
- {
- FuelLine thisTargetFuelLine = this.gameObject.GetComponentInChildren<FuelLine>();
- thisTargetFuelLine.fuelCrossFeed = false;
- print("Fuel line has taken damage!");
- }
- if (this.gameObject.GetComponentInChildren<ModuleReactionWheel>() == true)
- {
- ModuleReactionWheel thisTargetRWheel = this.gameObject.GetComponentInChildren<ModuleReactionWheel>();
- thisTargetRWheel.PitchTorque = rndNumber.rndFloat(0f, 10f);
- thisTargetRWheel.RollTorque = rndNumber.rndFloat(0f, 10f);
- thisTargetRWheel.YawTorque = rndNumber.rndFloat(0f, 10f);
- float chanceToBreak = (float)rndNumber.rndDouble(0.01, 50.0) * projPenetrate; // base chance to die
- float makeBreakRoll = rndNumber.rndRoll(0,100);
- if (chanceToBreak > makeBreakRoll)
- {
- thisTargetRWheel.wheelState = ModuleReactionWheel.WheelState.Broken;
- }
- print("Reaction Wheel is not working properly!");
- }
- if (this.gameObject.GetComponentInChildren<Light>() == true)
- {
- Light thisTargetLight = this.gameObject.GetComponentInChildren<Light>();
- thisTargetLight.enabled = false;
- if (this.gameObject.GetComponentInChildren<ModuleLight>() == true)
- {
- ModuleLight thisTargetLightModule = this.gameObject.GetComponentInChildren<ModuleLight>();
- thisTargetLightModule.isOn = false;
- thisTargetLightModule.LightsOff();
- }
- print("Light was damaged");
- }
- if (this.gameObject.GetComponentInChildren<projectileWS>() == true)
- {
- projectileWS thisTargetGun = this.gameObject.GetComponentInChildren<projectileWS>();
- thisTargetGun.ctrlTurret = false;
- thisTargetGun.fireOverride = true;
- print("This ID gun is out of action!!!");
- }
- if (this.gameObject.GetComponentInChildren<CommandPod>() == true)
- {
- CommandPod thisTargetCommand = this.gameObject.GetComponentInChildren<CommandPod>();
- thisTargetCommand.Kd = rndNumber.rndRoll(0, 1);
- thisTargetCommand.Kp = rndNumber.rndRoll(0, 1);
- thisTargetCommand.linPower = rndNumber.rndRoll(0, 1);
- thisTargetCommand.rotPower = rndNumber.rndRoll(0, 1);
- float chanceToDie = (float)rndNumber.rndDouble(0.01, 20.0) * projPenetrate; // base chance to die
- float makeDieRoll = rndNumber.rndRoll(0,100);
- if (chanceToDie > makeDieRoll)
- {
- ProtoCrewMember getPilot = this.vessel.GetVesselCrew().FirstOrDefault();
- getPilot.Die();
- }
- }
- if (this.gameObject.GetComponentInChildren<LandingGear>() == true)
- {
- LandingGear thisTargetGear = this.gameObject.GetComponentInChildren<LandingGear>();
- thisTargetGear.frozen = true;
- }
- if (this.gameObject.GetComponentInChildren<ModuleWheel>() == true)
- {
- ModuleWheel thisTargetWheel = this.gameObject.GetComponentInChildren<ModuleWheel>();
- thisTargetWheel.isDamaged = true;
- }
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel")
- {
- fuelLeak = true;
- leakToLevel = resource.maxAmount * rndNumber.rndDouble(0.01, 1.0);
- }
- if (resource.resourceName == "ElectricCharge")
- {
- resource.flowMode = PartResource.FlowMode.None;
- resource.flowState = false;
- resource.amount = 0.0;
- }
- if (resource.resourceName.Contains("Ammo"))
- {
- float chanceToBlow = (float)rndNumber.rndDouble(0.01, 75.0) * projPenetrate;
- float makeBlowRoll = rndNumber.rndRoll(0,100);
- if (chanceToBlow > makeBlowRoll)
- {
- FXMonger.Explode(this.part, this.part.transform.position, (float)resource.amount);
- this.part.explode();
- }
- }
- }
- if (this.currentPartStructure < 0f)
- {
- this.currentPartStructure = 0f;
- }
- }
- }
- public void enablePartFunctions()
- {
- if (this.gameObject.GetComponentInChildren<ModuleEngines>() == true)
- {
- ModuleEngines thisTargetEngine = this.gameObject.GetComponentInChildren<ModuleEngines>();
- thisTargetEngine.allowRestart = true;
- thisTargetEngine.enabled = true;
- }
- if (this.gameObject.GetComponentInChildren<ModuleEnginesFX>() == true)
- {
- ModuleEnginesFX thisTargetEngine = this.gameObject.GetComponentInChildren<ModuleEnginesFX>();
- thisTargetEngine.allowRestart = true;
- thisTargetEngine.isEnabled = true;
- }
- if (this.gameObject.GetComponentInChildren<ControlSurface>() == true)
- {
- ControlSurface thisTargetSurface = this.gameObject.GetComponentInChildren<ControlSurface>();
- thisTargetSurface.ctrlSurfaceRange = 20f;
- thisTargetSurface.deflectionLiftCoeff = wingOriginalSurfaceArea;
- print("control surface is fixed");
- }
- if (this.gameObject.GetComponentInChildren<FuelLine>() == true)
- {
- FuelLine thisTargetFuelLine = this.gameObject.GetComponentInChildren<FuelLine>();
- thisTargetFuelLine.fuelCrossFeed = true;
- print("Fuel line repaired!");
- }
- if (this.gameObject.GetComponentInChildren<ModuleReactionWheel>() == true)
- {
- ModuleReactionWheel thisTargetRWheel = this.gameObject.GetComponentInChildren<ModuleReactionWheel>();
- thisTargetRWheel.PitchTorque = 10f;
- thisTargetRWheel.RollTorque = 10f;
- thisTargetRWheel.YawTorque = 10f;
- thisTargetRWheel.wheelState = ModuleReactionWheel.WheelState.Active;
- print("Reaction Wheel is fixed!");
- }
- if (this.gameObject.GetComponentInChildren<Light>() == true)
- {
- Light thisTargetLight = this.gameObject.GetComponentInChildren<Light>();
- thisTargetLight.enabled = true;
- if (this.gameObject.GetComponentInChildren<ModuleLight>() == true)
- {
- ModuleLight thisTargetLightModule = this.gameObject.GetComponentInChildren<ModuleLight>();
- thisTargetLightModule.isOn = true;
- thisTargetLightModule.LightsOn();
- }
- print("Light is fixed");
- }
- if (this.gameObject.GetComponentInChildren<projectileWS>() == true)
- {
- projectileWS thisTargetGun = this.gameObject.GetComponentInChildren<projectileWS>();
- thisTargetGun.fireOverride = false;
- print("This ID gun is repaired!!!");
- }
- if (this.gameObject.GetComponentInChildren<CommandPod>() == true)
- {
- CommandPod thisTargetCommand = this.gameObject.GetComponentInChildren<CommandPod>();
- thisTargetCommand.Kd = 1f;
- thisTargetCommand.Kp = 1f;
- thisTargetCommand.linPower = 1f;
- thisTargetCommand.rotPower = 1f;
- }
- if (this.gameObject.GetComponentInChildren<LandingGear>() == true)
- {
- LandingGear thisTargetGear = this.gameObject.GetComponentInChildren<LandingGear>();
- thisTargetGear.frozen = false;
- }
- if (this.gameObject.GetComponentInChildren<ModuleWheel>() == true)
- {
- ModuleWheel thisTargetWheel = this.gameObject.GetComponentInChildren<ModuleWheel>();
- thisTargetWheel.isDamaged = false;
- }
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel")
- {
- fuelLeak = false;
- leakToLevel = resource.maxAmount;
- }
- if (resource.resourceName == "ElectricCharge")
- {
- resource.flowMode = PartResource.FlowMode.Both;
- resource.flowState = true;
- resource.amount = resource.maxAmount * 0.2f;
- }
- }
- }
- public void checkSinkSpread(targetPart sinkSel)
- {
- float chanceOfSink = (targetStructure / currentPartStructure) * 10;
- if (chanceOfSink <= 5) chanceOfSink = 5;
- int randomNumber = UnityEngine.Random.Range(0, 100);
- sinkCheckTime = (sinkCheckTime += 20);
- if (randomNumber < chanceOfSink)
- {
- setConditionS = true;
- }
- }
- public void checkMeshVolume()
- {
- float runningTotal = 0f;
- float totalAvg = 0f;
- MeshFilter[] getAllMeshes = base.part.GetComponentsInChildren<MeshFilter>();
- if (getAllMeshes != null || getAllMeshes.Length <= 0)
- {
- foreach (MeshFilter mF in getAllMeshes)
- {
- if (mF != null)
- {
- runningTotal += VolumeOfMesh(mF.sharedMesh);
- totalAvg = runningTotal / (float)getAllMeshes.Count();
- }
- }
- }
- thisPartMeshVolume = totalAvg;
- if (thisPartMeshVolume < 1f)
- {
- float isThisValueHigher = 0f;
- if (this.part.collider != null)
- {
- isThisValueHigher = (this.part.collider.bounds.size.y * this.part.collider.bounds.size.x * this.part.collider.bounds.size.z); //alternate sizing method
- }
- if (isThisValueHigher > thisPartMeshVolume) thisPartMeshVolume = isThisValueHigher;
- }
- //Known problem part list: Some stock parts have crazy values...
- if (this.part.partName.Contains("airScoop") || this.part.name == "airScoop" || base.part.partName == "airScoop")
- {
- thisPartMeshVolume = 0.15f;
- }
- if (this.part.partName.Contains("wingConnector") || this.part.name == "wingConnector" || base.part.partName == "wingConnector")
- {
- thisPartMeshVolume = 0.75f;
- }
- if (this.part.partName.Contains("structuralWing") || this.part.name == "structuralWing" || base.part.partName == "structuralWing")
- {
- thisPartMeshVolume = 0.85f;
- }
- if (this.part.partName.Contains("smallCtrlSrf") || this.part.name == "smallCtrlSrf" || base.part.partName == "smallCtrlSrf")
- {
- thisPartMeshVolume = 0.2f;
- }
- if (this.part.partName.Contains("StandardCtrlSrf") || this.part.name == "StandardCtrlSrf" || base.part.partName == "StandardCtrlSrf")
- {
- thisPartMeshVolume = 0.4f;
- }
- if (this.part.partName.Contains("CanardController") || this.part.name == "CanardController" || base.part.partName == "CanardController")
- {
- thisPartMeshVolume = 0.42f;
- }
- if (this.part.partName.Contains("deltaWing") || this.part.name == "deltaWing" || base.part.partName == "deltaWing")
- {
- thisPartMeshVolume = 1f;
- }
- if (this.part.partName.Contains("sweptWing") || this.part.name == "sweptWing" || base.part.partName == "sweptWing")
- {
- thisPartMeshVolume = 0.85f;
- }
- if (this.part.partName.Contains("tailfin") || this.part.name == "tailfin" || base.part.partName == "tailfin")
- {
- thisPartMeshVolume = 0.44f;
- //print(this.part.partName + " has been fixed");
- }
- if (this.part.partName.Contains("R8winglet") || this.part.name == "R8winglet" || base.part.partName == "R8winglet")
- {
- thisPartMeshVolume = 0.35f;
- }
- if (this.part.partName.Contains("winglet3") || this.part.name == "winglet3" || base.part.partName == "winglet3")
- {
- thisPartMeshVolume = 0.325f;
- }
- if (this.part.partName.Equals("winglet") || this.part.name == "winglet" || base.part.partName == "winglet")
- {
- thisPartMeshVolume = 0.315f;
- }
- if (this.part.partName.Contains("CircularIntake") || this.part.name == "CircularIntake" || base.part.partName == "CircularIntake")
- {
- thisPartMeshVolume = 0.15f;
- }
- if (this.part.partName.Contains("ramAirIntake") || this.part.name == "ramAirIntake" || base.part.partName == "ramAirIntake")
- {
- thisPartMeshVolume = 0.25f;
- }
- if (this.part.partName.Contains("structuralPanel") || this.part.name == "structuralPanel" || base.part.partName == "structuralPanel")
- {
- targetHardness = 250f;
- }
- if (this.part.partName.Contains("roverBody") || this.part.name == "roverBody" || base.part.partName == "roverBody")
- {
- thisPartMeshVolume = 3.25f;
- targetHardness = 200f;
- }
- if (this.part.name.Contains("FSbomb") || this.part.name == "FStailWingLarge" || base.part.partName == "FSbomberFuselage")
- {
- targetHardness = 170f;
- targetNotVoid = 0.075f;
- }
- if (this.part.name.Contains("RepairStation") || this.part.name == "RepairStation" || base.part.partName == "RepairStation")
- {
- //print("Fixing Repair Station");
- targetHardness = 220f;
- targetNotVoid = 0.00000015f;
- }
- if (this.part.partName.Contains("roverWheel") || this.part.name == "roverWheel" || base.part.partName == "roverWheel" || this.part.partName.Contains("wheelMed"))
- {
- targetHardness = 250f;
- }
- }
- public void setFireFX()
- {
- if (this.part.mass >= 3.5f)
- {
- this.useFireFX = "IDSkillfulR1/Effects/largeFire/model";
- }
- }
- public void doIDExplode()
- {
- GameObject fxIDExplode = new GameObject();
- if (fxIDExplode == null || fxIDExplode.activeInHierarchy == false)
- {
- try
- {
- fxIDExplode = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/IDexplode/model");
- }
- catch
- {
- print("Problem locating IDexplode");
- }
- if (fxIDExplode != null)
- {
- fxIDExplode.SetActive(true);
- fxIDExplode.transform.position = this.part.transform.position;
- fxIDExplode.transform.parent = this.part.transform;
- fxIDExplode.AddComponent<endFx>();
- Destroy(fxIDExplode, 4f * this.part.mass);
- }
- }
- }
- public void checkFuelLoss()
- {
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "LiquidFuel")
- {
- resource.flowMode = PartResource.FlowMode.Out;
- if (resource.amount > leakToLevel)
- {
- resource.amount -= fLeakRate * TimeWarp.deltaTime;
- }
- }
- }
- }
- public void OnTriggerEnter(Collider theProjectile)
- {
- if (theProjectile.gameObject.GetComponent<impact>())
- {
- //print("Hitting Target Via Impact it has: " + currentPartStructure + " Structure");
- if (theProjectile.rigidbody.velocity.magnitude > 50f && currentPartStructure > 0f)
- {
- #region hit effects for parts *******************************************FX
- GameObject explosion = Part.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustSparks_yellow")) as GameObject;
- explosion.transform.localEulerAngles = Vector3.zero;
- explosion.transform.localPosition = new Vector3(0, 0, 0);
- explosion.transform.position = this.transform.position;
- ParticleEmitter emitter = explosion.particleEmitter;
- emitter.emit = false;
- emitter.minSize = theProjectile.rigidbody.mass * 20f + 0.35f;
- emitter.maxSize = theProjectile.rigidbody.mass * 50f + 0.75f;
- emitter.minEnergy = (theProjectile.rigidbody.mass * theProjectile.rigidbody.velocity.magnitude) * 0.003f;
- emitter.maxEnergy = (theProjectile.rigidbody.mass * theProjectile.rigidbody.velocity.magnitude) * 0.015f;
- emitter.rndVelocity = Vector3.one * ((float)rndNumber.rndDouble(0.01, 1.2) * 0.75f);
- emitter.localVelocity = Vector3.zero;
- emitter.useWorldSpace = true;
- ParticleAnimator emitterAnimator = emitter.GetComponent<ParticleAnimator>();
- emitterAnimator.sizeGrow = 0.03F;
- Color[] emitterColors = emitterAnimator.colorAnimation;
- emitterColors[0] = new Color(1f, 0f, 0f, 0.95f);
- emitterColors[1] = new Color(1f, 1f, 1f, 0.95f);
- emitterColors[2] = new Color(0.75f, 0.75f, 0.75f, 0.6f);
- emitterColors[3] = new Color(0.5f, 0.5f, 0.5f, 0.4f);
- emitterColors[4] = new Color(0f, 0f, 0f, 0.15f);
- emitterAnimator.colorAnimation = emitterColors;
- emitter.Emit(8);
- #endregion
- impact thisImpact = theProjectile.gameObject.GetComponent<impact>();
- this.vessel.GoOffRails();
- thisImpact.renderer.enabled = false;
- projectileMass = thisImpact.rb.mass;
- projectileVelocity = theProjectile.rigidbody.velocity.magnitude;
- projPenetrate = thisImpact.useProjPenetrate;
- projHardness = thisImpact.useHardness;
- warheadModifier = thisImpact.useWarheadType;
- checkPenetrate();
- Destroy(thisImpact.gameObject);
- }
- }
- else if (theProjectile.gameObject.GetComponent<fragImpact>() || theProjectile.gameObject.GetComponentInChildren<fragImpact>() || theProjectile.gameObject.GetComponentInParent<fragImpact>())
- {
- //print("Fragment hit Target Via FragImpact - it has: " + currentPartStructure + " Structure");
- fragImpact thisFImpact = theProjectile.gameObject.GetComponent<fragImpact>();
- if (thisFImpact != null)
- {
- fragImpactHandler = thisFImpact;
- thisBRB = thisFImpact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisFImpact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisFImpact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- fragImpact thisF2Impact = theProjectile.gameObject.GetComponentInChildren<fragImpact>();
- if (thisF2Impact != null)
- {
- fragImpactHandler = thisF2Impact;
- thisBRB = thisF2Impact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisF2Impact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisF2Impact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- fragImpact thisF3Impact = theProjectile.gameObject.GetComponentInParent<fragImpact>();
- if (thisF3Impact != null)
- {
- fragImpactHandler = thisF3Impact;
- thisBRB = thisF3Impact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisF3Impact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisF3Impact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- if (thisBRB.velocity.magnitude > 5f && currentPartStructure > 0f)
- {
- if (this.vessel != FlightGlobals.ActiveVessel) this.vessel.GoOffRails();
- projectileMass = fragImpactHandler.rigidbody.mass;
- projectileVelocity = fragImpactHandler.rigidbody.velocity.magnitude;
- projPenetrate = 400f;
- projHardness = fragImpactHandler.fragHardness;
- warheadModifier = fragImpactHandler.fragWarheadType;
- checkPenetrate();
- Destroy(fragImpactHandler.gameObject);
- }
- }
- else if (theProjectile.gameObject.GetComponent<IDDropBomb>() || theProjectile.gameObject.GetComponentInChildren<IDDropBomb>() || theProjectile.gameObject.GetComponentInParent<IDDropBomb>())
- {
- //print("Bomb hit Target Via Bomb Impact- it has: " + currentPartStructure + " Structure");
- IDDropBomb thisBImpact = theProjectile.gameObject.GetComponent<IDDropBomb>();
- if (thisBImpact != null)
- {
- thisBRB = thisBImpact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisBImpact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisBImpact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- IDDropBomb thisB2Impact = theProjectile.gameObject.GetComponentInChildren<IDDropBomb>();
- if (thisB2Impact != null)
- {
- thisBRB = thisB2Impact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisB2Impact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisB2Impact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- IDDropBomb thisB3Impact = theProjectile.gameObject.GetComponentInParent<IDDropBomb>();
- if (thisB3Impact != null)
- {
- thisBRB = thisB3Impact.gameObject.GetComponent<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisB3Impact.gameObject.GetComponentInChildren<Rigidbody>();
- if (thisBRB == null)
- {
- thisBRB = thisB3Impact.gameObject.GetComponentInParent<Rigidbody>();
- }
- }
- }
- if (thisBRB.velocity.magnitude > 5f && this.currentPartStructure > 0f && thisB3Impact.septimer > 0.25f)
- {
- FXMonger.Explode(this.part, this.part.transform.position, 0.1f + thisBRB.mass);
- thisB3Impact.terrainHit();
- if (this.vessel != FlightGlobals.ActiveVessel) this.vessel.GoOffRails();
- this.projHardness = thisB3Impact.isHardness;
- this.warheadModifier = thisB3Impact.isWarheadType;
- this.projPenetrate = 400f;
- this.projectileMass = thisBRB.mass;
- this.projectileVelocity = thisBRB.velocity.magnitude;
- this.hitIsTorpedo = thisB3Impact.isTorpedo;
- checkPenetrate();
- Destroy(thisB3Impact.gameObject);
- }
- //}
- }
- }
- public void checkKerbal()
- {
- CrewRoster crewRoster = HighLogic.CurrentGame.CrewRoster;
- ProtoCrewMember getStats = FlightGlobals.ActiveVessel.GetVesselCrew().FirstOrDefault();
- lastKerbalName = getStats.name;
- bool oneTime = true;
- foreach (ProtoCrewMember crewMember in crewRoster)
- {
- if (lastKerbalName == crewMember.name && oneTime == true)
- {
- ourKerbalsStupid = crewMember.stupidity;
- ourKerbalIsBadass = crewMember.isBadass;
- ourKerbalCourage = crewMember.courage;
- string showKerStats = crewMember.name + " has a technicial rating of " + (1f - ourKerbalsStupid);
- ScreenMessages.PostScreenMessage(new ScreenMessage(showKerStats, 3f, ScreenMessageStyle.UPPER_CENTER));
- oneTime = false;
- }
- }
- }
- }
- *****************************************************************Targetpart
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- public class IDtargeter : InternalModule
- {
- public Vector3 TlocXYZ;
- public Vector3 compareXYZ;
- public Vector3 targScaler;
- public Vector3 compareScale;
- public bool firstRunPersist;
- private bool firstRun = true;
- private bool foundSight = false;
- private bool gunSightOn = true;
- private Transform targeterTransform;
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA || CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Internal)
- {
- if (foundSight == false)
- {
- try
- {
- this.targeterTransform = internalProp.FindModelTransform("gunSight");
- print("Looking for part with gunSight");
- }
- catch
- {
- print("Finding the gunSight!");
- }
- if (this.targeterTransform != null)
- {
- foundSight = true;
- print("Found a gunSight!");
- }
- }
- if (firstRun == true && this.targeterTransform != null)
- {
- firstRunPersist = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().firstRunPersistMem;
- TlocXYZ = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem;
- targScaler = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().targScalerMem;
- if (firstRunPersist == true)
- {
- print("Initialize gunSight for the first time");
- TlocXYZ = new Vector3(-0.08f, 0.35f, -4.81f);
- targScaler = new Vector3(0.036f, 0.036f, 0.036f);
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().targScalerMem = targScaler;
- firstRunPersist = false;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().firstRunPersistMem = firstRunPersist;
- }
- compareXYZ = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem;
- if (this.targeterTransform.position != compareXYZ)
- {
- TlocXYZ = compareXYZ;
- this.targeterTransform.position = TlocXYZ;
- }
- compareScale = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().targScalerMem;
- if (this.targeterTransform.localScale != compareScale)
- {
- targScaler = compareScale;
- this.targeterTransform.localScale = targScaler;
- }
- firstRun = false;
- }
- if (this.vessel == FlightGlobals.ActiveVessel && this.targeterTransform != null)
- {
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.DownArrow))
- {
- TlocXYZ.z = TlocXYZ.z + 0.01f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.UpArrow))
- {
- TlocXYZ.z = TlocXYZ.z - 0.01f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.RightArrow))
- {
- TlocXYZ.x = TlocXYZ.x + 0.01f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.LeftArrow))
- {
- TlocXYZ.x = TlocXYZ.x - 0.01f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadMultiply))
- {
- TlocXYZ.y = TlocXYZ.y + 0.025f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadDivide))
- {
- TlocXYZ.y = TlocXYZ.y - 0.025f;
- this.targeterTransform.position = TlocXYZ;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadMinus))
- {
- float doScale = targScaler.x;
- doScale = doScale - 0.001f;
- targScaler = new Vector3(doScale, doScale, doScale);
- this.targeterTransform.localScale = targScaler;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().targScalerMem = targScaler;
- print("gunSight Smaller");
- print(TlocXYZ.x + ", " + TlocXYZ.y + ", " + TlocXYZ.z);
- print(targScaler.x + ", " + targScaler.y + ", " + targScaler.z);
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadPlus))
- {
- float doScale = targScaler.x;
- doScale = doScale + 0.001f;
- targScaler = new Vector3(doScale, doScale, doScale);
- this.targeterTransform.localScale = targScaler;
- this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault().targScalerMem = targScaler;
- print("gunSight Larger");
- print(TlocXYZ.x + ", " + TlocXYZ.y + ", " + TlocXYZ.z);
- print(targScaler.x + ", " + targScaler.y + ", " + targScaler.z);
- }
- if (gunSightOn == false && Input.GetKeyDown(KeyCode.Insert))
- {
- targeterTransform.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- }
- else if (gunSightOn == true && Input.GetKeyDown(KeyCode.Insert))
- {
- targeterTransform.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- }
- }
- }
- else
- { firstRun = true; }
- }
- }
- public class IDtargeterEXT : PartModule
- {
- public Vector3 TlocXYZ;
- public Vector3 compareXYZ;
- public Vector3 targScaler;
- public Vector3 compareScale;
- public bool firstRunPersist = true;
- private bool firstRun = true;
- private bool foundSight = false;
- private bool gunSightOn = true;
- private Transform targeterTransform;
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (foundSight == false)
- {
- try
- {
- targeterTransform = part.FindModelTransform("gunSight");
- print("Looking for part with gunSight");
- }
- catch
- {
- print("Finding the gunSight!");
- }
- if (targeterTransform != null)
- {
- foundSight = true;
- print("Found a gunSight!");
- }
- }
- if (firstRun == true && foundSight == true)
- {
- cockpitMemory thisMemory = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault();
- if (thisMemory != null)
- {
- firstRunPersist = thisMemory.firstRunPersistMem;
- }
- print("Initialize gunSight for the first time");
- TlocXYZ = new Vector3(0f, 0f, -9f);
- targeterTransform.localPosition = TlocXYZ;
- targScaler = new Vector3(0.036f, 0.036f, 0.036f);
- print("TlocXYZ = " + TlocXYZ);
- if (firstRunPersist == true)
- {
- thisMemory.TlocXYZMem = TlocXYZ;
- thisMemory.targScalerMem = targScaler;
- print("TlocXYZMem = " + thisMemory.TlocXYZMem);
- firstRunPersist = false;
- thisMemory.firstRunPersistMem = firstRunPersist;
- }
- compareXYZ = thisMemory.TlocXYZMem;
- if (this.targeterTransform.localPosition != compareXYZ)
- {
- TlocXYZ = compareXYZ;
- targeterTransform.localPosition = TlocXYZ;
- }
- compareScale = thisMemory.targScalerMem;
- if (this.targeterTransform.localScale != compareScale)
- {
- targScaler = compareScale;
- targeterTransform.localScale = targScaler;
- }
- firstRun = false;
- }
- else
- { firstRun = true; }
- }
- public void Update()
- {
- if (this.vessel == FlightGlobals.ActiveVessel && this.targeterTransform != null)
- {
- cockpitMemory thisMemory = this.vessel.FindPartModulesImplementing<cockpitMemory>().FirstOrDefault();
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.DownArrow))
- {
- TlocXYZ.z = TlocXYZ.z + 0.01f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.UpArrow))
- {
- TlocXYZ.z = TlocXYZ.z - 0.01f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.RightArrow))
- {
- TlocXYZ.x = TlocXYZ.x + 0.01f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.LeftArrow))
- {
- TlocXYZ.x = TlocXYZ.x - 0.01f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadMultiply))
- {
- TlocXYZ.y = TlocXYZ.y + 0.025f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadDivide))
- {
- TlocXYZ.y = TlocXYZ.y - 0.025f;
- this.targeterTransform.localPosition = TlocXYZ;
- thisMemory.TlocXYZMem = TlocXYZ;
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadMinus))
- {
- float doScale = targScaler.x;
- doScale = doScale - 0.001f;
- targScaler = new Vector3(doScale, doScale, doScale);
- this.targeterTransform.localScale = targScaler;
- thisMemory.targScalerMem = targScaler;
- print("gunSight Smaller");
- print(TlocXYZ.x + ", " + TlocXYZ.y + ", " + TlocXYZ.z);
- print(targScaler.x + ", " + targScaler.y + ", " + targScaler.z);
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKey(KeyCode.KeypadPlus))
- {
- float doScale = targScaler.x;
- doScale = doScale + 0.001f;
- targScaler = new Vector3(doScale, doScale, doScale);
- this.targeterTransform.localScale = targScaler;
- thisMemory.targScalerMem = targScaler;
- print("gunSight Larger");
- print(TlocXYZ.x + ", " + TlocXYZ.y + ", " + TlocXYZ.z);
- print(targScaler.x + ", " + targScaler.y + ", " + targScaler.z);
- }
- if (gunSightOn == false && Input.GetKeyDown(KeyCode.Insert))
- {
- targeterTransform.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- gunSightOn = true;
- }
- if (gunSightOn == true && Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.Insert))
- {
- targeterTransform.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- gunSightOn = false;
- }
- }
- }
- }
- public class cockpitMemory : PartModule
- {
- [KSPField(isPersistant = true)]
- public Vector3 TlocXYZMem;
- [KSPField(isPersistant = true)]
- public Vector3 targScalerMem;
- [KSPField(isPersistant = true)]
- public bool firstRunPersistMem = true;
- }
- *******************************************************IDtargeter
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- public class projectileWS : PartModule
- {
- public bool fireBurst = false;
- public bool proximitySet = false;
- [KSPField(guiActive = true, isPersistant = true)]
- public bool guardMode = false;
- [KSPField(guiActive = true, guiName = "Transfer Mode: ")]
- public bool transferAmmo = false;
- [KSPField(isPersistant = true, guiActiveEditor = false, guiActive = false, guiName = "CIWS Lead: "), UI_FloatRange(minValue = 0f, maxValue = 1f, stepIncrement = 0.025f)]
- public float guiLead = 0.375f;
- [KSPField(guiActive = true, isPersistant = true)]
- public bool ctrlTurret = false;
- [KSPField(guiActive = true, isPersistant = true)]
- public bool invertRotation = false;
- [KSPField(isPersistant = true)]
- public bool isAutoLoader = false;
- public string setIFF = "";
- public bool missileIFFDone = false;
- public GameObject bullet, bulletTwo, bulletThree;
- public GameObject leadTarget;
- public FXGroup soundGroup, soundGroup2, soundGroup3, soundGroup4, soundGroup5, soundGroup6;
- public GameObject fireCannonFX;
- public GameObject burstTrailFX;
- //public GameObject burstFlash;
- private Ray rayLOS;
- public RaycastHit hitLOS;
- public bool fireOverride = false;
- public bool tripOverride = false;
- public Vector3 currentTurretAngle;
- public Vector3 currentTurretLocation;
- private Transform turretTransform;
- private Transform muzzleFlashLight, muzzleFlashLightTwo, muzzleFlashLightThree;
- public bool hostileClosing = false;
- public bool takeOne = false;
- public Vessel hostileOne, hostileTwo, hostileThree, targetHostile;
- [KSPField]
- public float gunType = 0f;
- [KSPField]
- public float turretType = 0f;
- [KSPField]
- public bool isTurret = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "TurrSpd: "), UI_FloatRange(minValue = 0.1f, maxValue = 1f, stepIncrement = 0.1f)]
- public float turretSpeed = 1f;
- [KSPField]
- public bool isCIWS = false;
- [KSPField]
- public float bulletSpawns = 1f;
- [KSPField]
- public float detType = 0f;
- public float ammoBursts = 0f;
- [KSPField]
- public float projectileScale = 0.25f;
- [KSPField]
- public string ammoType = "none";
- [KSPField]
- public float ordHardness = 300f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "AmmoType: "), UI_FloatRange(minValue = 0f, maxValue = 3f, stepIncrement = 1f)]
- public float warheadType = 0f;
- [KSPField(guiActiveEditor = true, guiActive = true, guiName = "AmmoType: ")]
- public string warheadShow = "Kinetic";
- [KSPField(guiActiveEditor = false, guiActive = true, guiName = "Elevation: ")]
- public float elevateShow = 0;
- [KSPField]
- public float projKick = 0.45f;
- [KSPField]
- public string animatedPart = "none";
- [KSPField]
- public string animateDir = "X";
- [KSPField]
- public float animateDist = 0.001f;
- private Transform animateTransform;
- private Transform animateDefaultTransform;
- private bool firstRun = true;
- public bool animateMoved = false;
- [KSPField]
- public string animated2Part = "none";
- [KSPField]
- public string animate2Dir = "X";
- [KSPField]
- public float animate2Dist = 0.001f;
- private Transform animate2Transform;
- private Transform animate2DefaultTransform;
- public bool animate2Moved = false;
- public Transform turretBodyRotate;
- public Transform turretBarrelElevation;
- public float origTurretElevation = 0f;
- public float showTurretElevation = 0f;
- public float showTurretRotation = 0f;
- [KSPField(isPersistant = true)]
- public float ammoCap = 0f;
- [KSPField]
- public float rateOfFire = 10f;
- public float origRateOfFire = 10f;
- public float bulletCoolTimer = 10f;
- public float updateAmmoTimer = 30f;
- public float updateGunDirTimer = 300f;
- public float randomBurstTimer = 3f;
- [KSPField]
- public float projMass;
- [KSPField]
- public float projForce;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "AutoTrack: "), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool autoTrackOn = false;
- [KSPField]
- public bool smartTracking = false;
- public float leadMulti;
- [KSPField(isPersistant=true)]
- public bool hasActiveDirector = false;
- public gunDirector thisGunDirector;
- public float targetDistance = 0f;
- public AnimationCurve shotPrediction;
- [KSPField]
- public float bulletFXChance = 80f;
- [KSPField]
- public float bulletFXLife = 10f;
- [KSPField]
- public float projDrag;
- public float projPenetrate = 0f;
- [KSPEvent(active = true, guiName = "Reload Nearby", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 5f)]
- public void reloadCannon()
- {
- if (this.ammoBursts <= ammoCap)
- {
- float needsAmmo = ammoCap - this.ammoBursts;
- float takeAmmo = 0f;
- bool madeReload = false;
- PartResourceList resourceList = this.part.Resources;
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- if (Vector3.Distance(v.transform.position, this.transform.position) < 40f && v != this.vessel)
- {
- foreach (Part rPart in v.Parts)
- {
- foreach (PartModule rModule in rPart.Modules)
- {
- if(rModule is IDDepot)
- {
- PartResourceList rresourceList = rPart.Resources;
- foreach (PartResource rresource in rresourceList)
- {
- if (rresource.resourceName == ammoType && madeReload == false)
- {
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == ammoType)
- {
- if (rresource.amount > needsAmmo)
- {
- takeAmmo = needsAmmo;
- }
- else takeAmmo = (float)rresource.amount;
- rresource.amount -= (double)takeAmmo;
- resource.amount += (double)takeAmmo;
- ammoBursts = (int)resource.amount;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Found ammoType - adding from: " + v.vesselName, 8f, ScreenMessageStyle.UPPER_CENTER));
- //print("Found ammoType - adding from: " + v.vesselName);
- madeReload = true;
- }
- }
- }
- }
- }
- }
- }
- }
- else if (Vector3.Distance(v.transform.position, this.transform.position) > 40f && Vector3.Distance(v.transform.position, this.transform.position) < 250f)
- {
- //ScreenMessages.PostScreenMessage(new ScreenMessage("There is no vessel within 40m! Move closer!", 4f, ScreenMessageStyle.UPPER_CENTER));
- //print("There is no vessel within 40m! Move closer!");
- }
- }
- }
- }
- [KSPEvent(name = "fireburst", active = true, guiActive = true, guiName = "Fire Burst")]
- public void fireCannonBurst()
- {
- if (this.ammoBursts >= 1f && bulletCoolTimer <= 0f && fireOverride == false && transferAmmo == false)
- {
- //if (this.isTurret == true && turretType == 1f && ctrlTurret == false || ctrlTurret == false) //all now
- //{
- // //Debug.Log("Turret type 1 - no fire - control off!"); // testing, comment out later.
- //}
- //else
- //{
- fireBurst = true;
- fireCannonFX.particleEmitter.emit = true;
- //if (gunType == 0f) burstFlash.SetActive(true);
- #region Turn on lights for muzzle flashes
- if (bulletSpawns == 1)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- else if (bulletSpawns == 2)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- else if (bulletSpawns == 3)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightThree.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- #endregion
- this.ammoBursts = this.ammoBursts - this.bulletSpawns;
- //}
- }
- }
- [KSPEvent(name = "controlthis", active = true, guiActive = true, guiName = "Control This")]
- public void letsControlTurret()
- {
- if (ctrlTurret == false)
- {
- ctrlTurret = true;
- }
- else if (ctrlTurret == true)
- {
- ctrlTurret = false;
- }
- }
- [KSPEvent(name = "xferAmmo", active = true, guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 5f, guiName = "Transfer Ammo")]
- public void letsTransferAmmo()
- {
- if (transferAmmo == false)
- {
- transferAmmo = true;
- }
- else if (transferAmmo == true)
- {
- transferAmmo = false;
- }
- }
- [KSPEvent(name = "revrotation", active = true, guiActive = false, guiName = "Reverse Rotation")]
- public void letsRevRotation()
- {
- if (invertRotation == false)
- {
- invertRotation = true;
- }
- else if (invertRotation == true)
- {
- invertRotation = false;
- }
- }
- [KSPAction("Fire Cannon")]
- public void actFireCannon(KSPActionParam param)
- {
- if (param.type == KSPActionType.Activate)
- {
- fireCannonBurst();
- }
- }
- public override void OnStart(PartModule.StartState state)
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- base.OnStart(state);
- bulletCoolTimer = rateOfFire;
- origRateOfFire = rateOfFire;
- #region Set muzzle flash locations
- if (bulletSpawns == 1)
- {
- this.muzzleFlashLight = part.FindModelTransform("mFlash");
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- }
- else if (bulletSpawns == 2)
- {
- this.muzzleFlashLight = part.FindModelTransform("mFlash");
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- this.muzzleFlashLightTwo = part.FindModelTransform("mFlashTwo");
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- }
- else if (bulletSpawns == 3)
- {
- this.muzzleFlashLight = part.FindModelTransform("mFlash");
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- this.muzzleFlashLightTwo = part.FindModelTransform("mFlashTwo");
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- this.muzzleFlashLightThree = part.FindModelTransform("mFlashThree");
- this.muzzleFlashLightThree.GetComponents<Light>().FirstOrDefault().enabled = false; //starts off!
- }
- #endregion
- leadTarget = GameObject.CreatePrimitive(PrimitiveType.Cube);
- leadTarget.SetActive(false);
- leadTarget.renderer.enabled = false;
- Destroy(leadTarget.rigidbody);
- leadTarget.collider.enabled = false;
- if (turretType == 0 && isTurret == true)
- {
- turretTransform = part.FindModelTransform("Turret");
- }
- if (turretType == 1 && isTurret == true)
- {
- turretBodyRotate = part.FindModelTransform("turretBody");
- turretBarrelElevation = part.FindModelTransform("turretElevator");
- origTurretElevation = turretBarrelElevation.eulerAngles.z;
- //Events["letsControlTurret"].guiActive = true;
- //Events["letsRevRotation"].guiActive = true;
- }
- if (isAutoLoader == true)
- {
- Events["letsTransferAmmo"].guiActive = true;
- }
- #region Pull IFF
- if(this.setIFF == "")
- {
- foreach (Part p in vessel.parts)
- {
- PartModule m = p.GetComponent<PartModule>();
- if (m is relayIFF)
- {
- relayIFF checkIFF = m.GetComponent<relayIFF>();
- this.setIFF = checkIFF.setIFF;
- }
- }
- }
- #endregion
- #region Sound effects
- if (!GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/fastBurst") || !GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/singleCannon") || !GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/IDinternalMG") || !GameDatabase.Instance.ExistsAudioClip("IDSkillfulR1/Sounds/largeCannon")) return;
- soundGroup.audio = gameObject.AddComponent<AudioSource>();
- soundGroup2.audio = gameObject.AddComponent<AudioSource>();
- soundGroup3.audio = gameObject.AddComponent<AudioSource>();
- soundGroup4.audio = gameObject.AddComponent<AudioSource>();
- soundGroup5.audio = gameObject.AddComponent<AudioSource>();
- soundGroup6.audio = gameObject.AddComponent<AudioSource>();
- #region machineGun
- if (soundGroup.audio != null && gunType == 3)
- {
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup.audio.loop = false;
- soundGroup.audio.playOnAwake = false;
- soundGroup.audio.priority = 1;
- }
- if (soundGroup2.audio != null && gunType == 3)
- {
- soundGroup2.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup2.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup2.audio.dopplerLevel = 0f;
- soundGroup2.audio.panLevel = 1f;
- soundGroup2.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup2.audio.loop = false;
- soundGroup2.audio.playOnAwake = false;
- soundGroup2.audio.priority = 2;
- }
- if (soundGroup3.audio != null && gunType == 3)
- {
- soundGroup3.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup3.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup3.audio.dopplerLevel = 0f;
- soundGroup3.audio.panLevel = 1f;
- soundGroup3.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup3.audio.loop = false;
- soundGroup3.audio.playOnAwake = false;
- soundGroup3.audio.priority = 3;
- }
- if (soundGroup4.audio != null && gunType == 3)
- {
- soundGroup4.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup4.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup4.audio.dopplerLevel = 0f;
- soundGroup4.audio.panLevel = 1f;
- soundGroup4.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup4.audio.loop = false;
- soundGroup4.audio.playOnAwake = false;
- soundGroup4.audio.priority = 4;
- }
- if (soundGroup5.audio != null && gunType == 3)
- {
- soundGroup5.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup5.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup5.audio.dopplerLevel = 0f;
- soundGroup5.audio.panLevel = 1f;
- soundGroup5.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup5.audio.loop = false;
- soundGroup5.audio.playOnAwake = false;
- soundGroup5.audio.priority = 5;
- }
- if (soundGroup6.audio != null && gunType == 3)
- {
- soundGroup6.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup6.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup6.audio.dopplerLevel = 0f;
- soundGroup6.audio.panLevel = 1f;
- soundGroup6.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/IDinternalMG");
- soundGroup6.audio.loop = false;
- soundGroup6.audio.playOnAwake = false;
- soundGroup6.audio.priority = 6;
- }
- #endregion
- if (soundGroup.audio != null && gunType == 2)
- {
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/fastBurst");
- soundGroup.audio.loop = false;
- soundGroup.audio.playOnAwake = false;
- soundGroup.audio.priority = 1;
- }
- if (soundGroup.audio != null && gunType == 1)
- {
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/singleCannon");
- soundGroup.audio.loop = false;
- soundGroup.audio.playOnAwake = false;
- soundGroup.audio.priority = 1;
- }
- if (soundGroup.audio != null && gunType == 0)
- {
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("IDSkillfulR1/Sounds/largeCannon");//change later
- soundGroup.audio.loop = false;
- soundGroup.audio.playOnAwake = false;
- soundGroup.audio.priority = 1;
- }
- #endregion
- #region Particle Effects
- fireCannonFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_smokeTrail_light"));
- fireCannonFX.particleEmitter.emit = false;
- fireCannonFX.transform.parent = (muzzleFlashLight.transform);
- fireCannonFX.transform.localPosition = new Vector3(0, 0, 0.2f);
- fireCannonFX.transform.localRotation = this.part.transform.rotation;
- fireCannonFX.particleEmitter.useWorldSpace = true;
- fireCannonFX.particleEmitter.minSize = 1f;
- fireCannonFX.particleEmitter.maxSize = 3f;
- fireCannonFX.particleEmitter.localVelocity = new Vector3(0, 0, 1.5f);
- fireCannonFX.particleEmitter.maxEnergy = 7f;
- fireCannonFX.particleEmitter.minEmission = 120f;
- fireCannonFX.particleEmitter.angularVelocity = 0.01f;
- fireCannonFX.particleEmitter.rndRotation = false;
- //if (burstFlash == null && this.gunType == 0f)
- //{
- // try
- // {
- // burstFlash = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/largeBlast/model");
- // }
- // catch
- // {
- // print("Problem locating largeBlast FX!");
- // }
- // if (burstFlash != null)
- // {
- // Transform barrel1Blast = part.FindModelTransform("spawnBullet");
- // burstFlash.SetActive(false);
- // burstFlash.transform.position = barrel1Blast.position;
- // burstFlash.transform.parent = barrel1Blast;
- // burstFlash.transform.localRotation = barrel1Blast.localRotation;
- // burstFlash.gameObject.layer = 0;
- // }
- //}
- #endregion
- }
- public override void OnAwake()
- {
- base.OnAwake();
- if (turretType == 0 && isTurret == true)
- {
- turretTransform = part.FindModelTransform("Turret");
- }
- if (turretType == 1 && isTurret == true)
- {
- turretBodyRotate = part.FindModelTransform("turretBody");
- turretBarrelElevation = part.FindModelTransform("turretElevator");
- Events["letsControlTurret"].guiActive = true;
- }
- }
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (Input.GetKey(KeyCode.Home) && this.vessel == FlightGlobals.ActiveVessel)
- {
- if (this.ammoBursts >= 1f && bulletCoolTimer <= 0f && fireOverride == false && transferAmmo == false)
- {
- if (this.isTurret == true && turretType == 1f && ctrlTurret == false || ctrlTurret == false) //all now
- {
- //Debug.Log("Turret type 1 - no fire - control off!");
- }
- else
- {
- fireBurst = true;
- fireCannonFX.particleEmitter.emit = true;
- //if(gunType == 0f) burstFlash.SetActive(true);
- #region Turn on lights for muzzle flashes
- if (bulletSpawns == 1)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- else if (bulletSpawns == 2)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- else if (bulletSpawns == 3)
- {
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = true;
- this.muzzleFlashLightThree.GetComponents<Light>().FirstOrDefault().enabled = true;
- }
- #endregion
- this.ammoBursts = this.ammoBursts - this.bulletSpawns;
- }
- }
- }
- }
- public void FixedUpdate()
- {
- #region attach to rotating part
- #endregion
- if (warheadType == 0f) warheadShow = "Kinetic";
- if (warheadType == 1f) warheadShow = "HE";
- if (warheadType == 2f)
- {
- warheadShow = "Incend";
- ordHardness = 220f;
- }
- if (warheadType == 3f) warheadShow = "AP";
- if (turretType == 0f && isTurret == true)
- {
- Fields["guiLead"].guiActive = true;
- Fields["guiLead"].guiActiveEditor = true;
- Fields["invertRotation"].guiActive = false;
- Fields["invertRotation"].guiActiveEditor = false;
- Fields["turretSpeed"].guiActive = false;
- Fields["turretSpeed"].guiActiveEditor = false;
- Fields["elevateShow"].guiActive = false;
- Fields["elevateShow"].guiActiveEditor = false;
- }
- if (turretType == 1f && isTurret == true)
- {
- Fields["guiLead"].guiActive = false;
- Fields["guiLead"].guiActiveEditor = false;
- Fields["guardMode"].guiActive = false;
- Fields["guardMode"].guiActiveEditor = false;
- Fields["autoTrackOn"].guiActive = false;
- Fields["autoTrackOn"].guiActiveEditor = false;
- elevateShow = showTurretElevation;
- }
- if (isTurret == false)
- {
- Fields["elevateShow"].guiActive = false;
- Fields["elevateShow"].guiActiveEditor = false;
- Fields["guiLead"].guiActive = false;
- Fields["guiLead"].guiActiveEditor = false;
- Fields["ctrlTurret"].guiActive = true;
- Fields["ctrlTurret"].guiActiveEditor = true;
- Fields["invertRotation"].guiActive = false;
- Fields["invertRotation"].guiActiveEditor = false;
- Fields["turretSpeed"].guiActive = false;
- Fields["turretSpeed"].guiActiveEditor = false;
- Fields["guardMode"].guiActive = false;
- Fields["guardMode"].guiActiveEditor = false;
- Fields["autoTrackOn"].guiActive = false;
- Fields["autoTrackOn"].guiActiveEditor = false;
- }
- if (HighLogic.LoadedSceneIsFlight)
- {
- autoTracker();
- if (turretType == 0 && isTurret == true)
- {
- safetyLOS();
- }
- if (firstRun == true)
- {
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == ammoType)
- {
- ammoBursts = (int)resource.amount;
- //print("Found " + resource.resourceName + " : " + ammoBursts);
- }
- }
- if (ammoType == "762mmAmmo") projPenetrate = 1.75f;
- if (ammoType == "30calAmmo") projPenetrate = 2f;
- if (ammoType == "50calAmmo") projPenetrate = 2.5f;
- if (ammoType == "30mmAmmo") projPenetrate = 6f;
- if (ammoType == "5inchAmmo") projPenetrate = 66f;
- if (ammoType == "14inchAmmo") projPenetrate = 100f;
- if (animatedPart != "none")
- {
- //print("Initialize the animatePart code");
- animateTransform = part.FindModelTransform(animatedPart);
- if (animateTransform != null && firstRun == true)
- {
- animateDefaultTransform = new GameObject().transform;
- animateDefaultTransform = animateTransform;
- animateDefaultTransform.localPosition = animateTransform.localPosition;
- //print("animatePart found and set!");
- }
- }
- if (animated2Part != "none")
- {
- //print("Initialize the animate2Part code");
- animate2Transform = part.FindModelTransform(animated2Part);
- if (animate2Transform != null && firstRun == true)
- {
- animate2DefaultTransform = new GameObject().transform;
- animate2DefaultTransform = animate2Transform;
- animate2DefaultTransform.localPosition = animate2Transform.localPosition;
- //print("animate2Part found and set!");
- }
- }
- if (turretType == 1 && isTurret == true)
- {
- origTurretElevation = turretBarrelElevation.rotation.Pitch();
- if (this.vessel.isActiveVessel)
- {
- checkGunDirector();
- }
- }
- firstRun = false;
- }
- if (updateGunDirTimer > 0f && this.vessel.isActiveVessel)
- {
- updateGunDirTimer--;
- if (updateGunDirTimer <= 0f)
- {
- checkGunDirector();
- updateGunDirTimer = 300f;
- }
- }
- if (updateAmmoTimer > 0f)
- {
- updateAmmoTimer--;
- if (updateAmmoTimer <= 0f)
- {
- //if (burstFlash != null)
- //{
- // if (burstFlash.activeInHierarchy == true)
- // {
- // burstFlash.SetActive(false);
- // }
- //}
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == ammoType)
- {
- if (transferAmmo == false)
- {
- resource.amount = ammoBursts;
- }
- else ammoBursts = (float)resource.amount;
- }
- }
- updateAmmoTimer = 30f;
- }
- }
- if (bulletCoolTimer > 0f)
- {
- bulletCoolTimer--;
- }
- else
- {
- if (animateTransform != null && animateMoved == true)
- {
- if (animateDir == "Y")
- {
- animateTransform.localPosition = animateTransform.localPosition - new Vector3(0f, animateDist, 0f);
- }
- if (animateDir == "X")
- {
- animateTransform.localPosition = animateTransform.localPosition - new Vector3(animateDist, 0f, 0f);
- }
- if (animateDir == "Z")
- {
- animateTransform.localPosition = animateTransform.localPosition - new Vector3(0f, 0f, animateDist);
- }
- animateMoved = false;
- }
- if (animate2Transform != null && animate2Moved == true)
- {
- if (animate2Dir == "Y")
- {
- animate2Transform.localPosition = animate2Transform.localPosition - new Vector3(0f, animate2Dist, 0f);
- }
- if (animate2Dir == "X")
- {
- animate2Transform.localPosition = animate2Transform.localPosition - new Vector3(animate2Dist, 0f, 0f);
- }
- if (animate2Dir == "Z")
- {
- animate2Transform.localPosition = animate2Transform.localPosition - new Vector3(0f, 0f, animate2Dist);
- }
- animate2Moved = false;
- }
- }
- if (fireBurst == true)
- {
- if (soundGroup.audio.isPlaying == false)
- {
- soundGroup.audio.Play();
- }
- else if (soundGroup2.audio.isPlaying == false)
- {
- soundGroup2.audio.Play();
- }
- else if (soundGroup3.audio.isPlaying == false)
- {
- soundGroup3.audio.Play();
- }
- else if (soundGroup4.audio.isPlaying == false)
- {
- soundGroup4.audio.Play();
- }
- else if (soundGroup5.audio.isPlaying == false)
- {
- soundGroup5.audio.Play();
- }
- else if (soundGroup6.audio.isPlaying == false)
- {
- soundGroup6.audio.Play();
- }
- if (animateTransform != null && animateTransform.localPosition == animateDefaultTransform.localPosition)
- {
- if (animateDir == "Y")
- {
- animateTransform.localPosition = animateTransform.localPosition + new Vector3(0f, animateDist, 0f);
- }
- if (animateDir == "X")
- {
- animateTransform.localPosition = animateTransform.localPosition + new Vector3(animateDist, 0f, 0f);
- }
- if (animateDir == "Z")
- {
- animateTransform.localPosition = animateTransform.localPosition + new Vector3(0f, 0f, animateDist);
- }
- animateMoved = true;
- }
- if (animate2Transform != null && animate2Transform.localPosition == animate2DefaultTransform.localPosition)
- {
- if (animate2Dir == "Y")
- {
- animate2Transform.localPosition = animate2Transform.localPosition + new Vector3(0f, animate2Dist, 0f);
- }
- if (animate2Dir == "X")
- {
- animate2Transform.localPosition = animate2Transform.localPosition + new Vector3(animate2Dist, 0f, 0f);
- }
- if (animate2Dir == "Z")
- {
- animate2Transform.localPosition = animate2Transform.localPosition + new Vector3(0f, 0f, animate2Dist);
- }
- animate2Moved = true;
- }
- placeBulletEvent();
- fireBurst = false;
- }
- if (this.vessel != FlightGlobals.ActiveVessel && turretType == 0 && isTurret == true)
- {
- guardMode = true;
- }
- if (this.vessel == FlightGlobals.ActiveVessel && turretType == 0 && isTurret == true)
- {
- guardMode = false;
- }
- }
- }
- public void placeBulletEvent()
- {
- bullet = GameObject.CreatePrimitive(PrimitiveType.Cube);
- bullet.gameObject.transform.localScale.Set(projectileScale, projectileScale, projectileScale);
- bullet.SetActive(true);
- bullet.renderer.enabled = false;
- if (autoTrackOn == true && turretType == 0 && isTurret == true)
- {
- Transform placeItHere = (transform.Find("model/Rotator/Turret/spawnBullet"));
- bullet.transform.position = placeItHere.position;
- bullet.transform.rotation = placeItHere.rotation;
- bullet.transform.rotation *= Quaternion.Euler(90, 0, 0);
- }
- else if (autoTrackOn == false && turretType != 1 || isTurret == false)
- {
- Transform placeItHere = (transform.Find("model/spawnBullet"));
- bullet.transform.position = placeItHere.position;
- bullet.transform.rotation = placeItHere.rotation;
- }
- #region Turret Multi Barrel
- if (turretType == 1)
- {
- if (bulletSpawns == 1)
- {
- Transform placeItHere = part.FindModelTransform("spawnBullet");
- bullet.transform.position = placeItHere.position;
- bullet.transform.rotation = placeItHere.rotation;
- }
- if (bulletSpawns == 2)
- {
- Transform placeItHere = (transform.Find("model/Turret/turretBody/turretElevator/spawnBullet"));
- bullet.transform.position = placeItHere.position;
- bullet.transform.rotation = placeItHere.rotation;
- bullet.transform.rotation *= Quaternion.Euler(0f, 0f, 0f);
- bulletTwo = GameObject.CreatePrimitive(PrimitiveType.Cube);
- bulletTwo.SetActive(true);
- bulletTwo.renderer.enabled = false;
- Transform placeItHereTwo = (transform.Find("model/Turret/turretBody/turretElevator/spawnBulletTwo"));
- bulletTwo.transform.position = placeItHereTwo.position;
- bulletTwo.transform.rotation = placeItHereTwo.rotation;
- Rigidbody rbTwo = bulletTwo.AddComponent<Rigidbody>();
- rbTwo.collider.enabled = true;
- rbTwo.collider.isTrigger = true;
- rbTwo.useGravity = true;
- rbTwo.detectCollisions = true;
- rbTwo.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rbTwo.mass = projMass;
- rbTwo.drag = projDrag;
- rbTwo.velocity = this.vessel.rigidbody.velocity;
- rbTwo.AddForce(rbTwo.transform.up * projForce, ForceMode.Impulse);
- impact imp2 = bulletTwo.AddComponent<impact>();
- imp2.useHardness = this.ordHardness;
- imp2.useWarheadType = this.warheadType;
- imp2.useProjPenetrate = this.projPenetrate;
- imp2.bulletHoleChance = bulletFXChance;
- imp2.bulletHoleTime = bulletFXLife;
- imp2.wasDirected = hasActiveDirector;
- burstTrailFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustFlame_yellow_tiny"));
- burstTrailFX.particleEmitter.emit = true;
- burstTrailFX.transform.parent = (bulletTwo.transform);
- burstTrailFX.transform.localPosition = new Vector3(0, 0, 0);
- burstTrailFX.transform.rotation = bulletTwo.transform.rotation;
- burstTrailFX.particleEmitter.useWorldSpace = false;
- burstTrailFX.particleEmitter.minSize = 0.3f;
- burstTrailFX.particleEmitter.maxSize = 0.3f;
- burstTrailFX.particleEmitter.localVelocity = new Vector3(0, 0, 0);
- burstTrailFX.particleEmitter.minEnergy = 15f;
- burstTrailFX.particleEmitter.maxEnergy = 15f;
- burstTrailFX.particleEmitter.minEmission = 35f;
- burstTrailFX.particleEmitter.maxEmission = 35f;
- burstTrailFX.particleEmitter.angularVelocity = 0.01f;
- burstTrailFX.particleEmitter.rndRotation = false;
- this.rigidbody.AddForce(-muzzleFlashLight.up * (projForce * projKick), ForceMode.Impulse);
- Destroy(burstTrailFX.gameObject, 1.25f);
- if (gunType == 3) Destroy(bulletTwo.gameObject, 4f);
- if (gunType == 2) Destroy(bulletTwo.gameObject, 4f);
- if (gunType == 1) Destroy(bulletTwo.gameObject, 7f);
- if (gunType == 0) Destroy(bulletTwo.gameObject, 95f);
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = false;
- }
- if (bulletSpawns == 3)
- {
- Transform placeItHere = (transform.Find("model/Turret/turretBody/turretElevator/spawnBullet"));
- bullet.transform.position = placeItHere.position;
- bullet.transform.rotation = placeItHere.rotation;
- bullet.transform.rotation *= Quaternion.Euler(0f, 0f, 0f);
- bulletTwo = GameObject.CreatePrimitive(PrimitiveType.Cube);
- bulletTwo.SetActive(true);
- bulletTwo.renderer.enabled = false;
- Transform placeItHereTwo = (transform.Find("model/Turret/turretBody/turretElevator/spawnBulletTwo"));
- bulletTwo.transform.position = placeItHereTwo.position;
- bulletTwo.transform.rotation = placeItHereTwo.rotation;
- Rigidbody rbTwo = bulletTwo.AddComponent<Rigidbody>();
- rbTwo.collider.enabled = true;
- rbTwo.collider.isTrigger = true;
- rbTwo.useGravity = true;
- rbTwo.detectCollisions = true;
- rbTwo.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rbTwo.mass = projMass;
- rbTwo.drag = projDrag;
- rbTwo.velocity = this.vessel.rigidbody.velocity;
- rbTwo.AddForce(rbTwo.transform.up * projForce, ForceMode.Impulse);
- impact imp2 = bulletTwo.AddComponent<impact>();
- imp2.useHardness = this.ordHardness;
- imp2.useWarheadType = this.warheadType;
- imp2.useProjPenetrate = this.projPenetrate;
- imp2.bulletHoleChance = bulletFXChance;
- imp2.bulletHoleTime = bulletFXLife;
- imp2.wasDirected = hasActiveDirector;
- burstTrailFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustFlame_yellow_tiny"));
- burstTrailFX.particleEmitter.emit = true;
- burstTrailFX.transform.parent = (bulletTwo.transform);
- burstTrailFX.transform.localPosition = new Vector3(0, 0, 0);
- burstTrailFX.transform.rotation = bulletTwo.transform.rotation;
- burstTrailFX.particleEmitter.useWorldSpace = false;
- burstTrailFX.particleEmitter.minSize = 0.3f;
- burstTrailFX.particleEmitter.maxSize = 0.3f;
- burstTrailFX.particleEmitter.localVelocity = new Vector3(0, 0, 0);
- burstTrailFX.particleEmitter.minEnergy = 15f;
- burstTrailFX.particleEmitter.maxEnergy = 15f;
- burstTrailFX.particleEmitter.minEmission = 35f;
- burstTrailFX.particleEmitter.maxEmission = 35f;
- burstTrailFX.particleEmitter.angularVelocity = 0.01f;
- burstTrailFX.particleEmitter.rndRotation = false;
- this.rigidbody.AddForce(-muzzleFlashLight.up * (projForce * projKick), ForceMode.Impulse);
- Destroy(burstTrailFX.gameObject, 1.25f);
- if (gunType == 3) Destroy(bulletTwo.gameObject, 4f);
- if (gunType == 2) Destroy(bulletTwo.gameObject, 4f);
- if (gunType == 1) Destroy(bulletTwo.gameObject, 7f);
- if (gunType == 0) Destroy(bulletTwo.gameObject, 95f);
- this.muzzleFlashLightTwo.GetComponents<Light>().FirstOrDefault().enabled = false;
- bulletThree = GameObject.CreatePrimitive(PrimitiveType.Cube);
- bulletThree.SetActive(true);
- bulletThree.renderer.enabled = false;
- Transform placeItHereThree = (transform.Find("model/Turret/turretBody/turretElevator/spawnBulletThree"));
- bulletThree.transform.position = placeItHereThree.position;
- bulletThree.transform.rotation = placeItHereThree.rotation;
- Rigidbody rbThree = bulletThree.AddComponent<Rigidbody>();
- rbThree.collider.enabled = true;
- rbThree.collider.isTrigger = true;
- rbThree.useGravity = true;
- rbThree.detectCollisions = true;
- rbThree.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rbThree.mass = projMass;
- rbThree.drag = projDrag;
- rbThree.velocity = this.vessel.rigidbody.velocity;
- rbThree.AddForce(rbThree.transform.up * projForce, ForceMode.Impulse);
- impact imp3 = bullet.AddComponent<impact>();
- imp3.useHardness = this.ordHardness;
- imp3.useWarheadType = this.warheadType;
- imp3.useProjPenetrate = this.projPenetrate;
- imp3.bulletHoleChance = bulletFXChance;
- imp3.bulletHoleTime = bulletFXLife;
- imp3.wasDirected = hasActiveDirector;
- burstTrailFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustFlame_yellow_tiny"));
- burstTrailFX.particleEmitter.emit = true;
- burstTrailFX.transform.parent = (bulletThree.transform);
- burstTrailFX.transform.localPosition = new Vector3(0, 0, 0);
- burstTrailFX.transform.rotation = bulletThree.transform.rotation;
- burstTrailFX.particleEmitter.useWorldSpace = false;
- burstTrailFX.particleEmitter.minSize = 0.3f;
- burstTrailFX.particleEmitter.maxSize = 0.3f;
- burstTrailFX.particleEmitter.localVelocity = new Vector3(0, 0, 0);
- burstTrailFX.particleEmitter.minEnergy = 15f;
- burstTrailFX.particleEmitter.maxEnergy = 15f;
- burstTrailFX.particleEmitter.minEmission = 35f;
- burstTrailFX.particleEmitter.maxEmission = 35f;
- burstTrailFX.particleEmitter.angularVelocity = 0.01f;
- burstTrailFX.particleEmitter.rndRotation = false;
- this.rigidbody.AddForce(-muzzleFlashLight.up * (projForce * projKick), ForceMode.Impulse);
- Destroy(burstTrailFX.gameObject, 1.25f);
- if (gunType == 3) Destroy(bulletThree.gameObject, 4f);
- if (gunType == 2) Destroy(bulletThree.gameObject, 4f);
- if (gunType == 1) Destroy(bulletThree.gameObject, 7f);
- if (gunType == 0) Destroy(bulletThree.gameObject, 95f);
- this.muzzleFlashLightThree.GetComponents<Light>().FirstOrDefault().enabled = false;
- }
- }
- #endregion
- Rigidbody rb = bullet.AddComponent<Rigidbody>(); // ***********************
- rb.collider.enabled = true;
- rb.collider.isTrigger = true;
- rb.useGravity = true;
- rb.detectCollisions = true;
- rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rb.mass = projMass;
- rb.drag = projDrag;
- rb.velocity = this.vessel.rigidbody.velocity;
- rb.AddForce(rb.transform.up * projForce, ForceMode.Impulse);
- impact imp = bullet.AddComponent<impact>();
- imp.useHardness = this.ordHardness;
- imp.useWarheadType = this.warheadType;
- imp.useProjPenetrate = this.projPenetrate;
- imp.bulletHoleChance = bulletFXChance;
- imp.bulletHoleTime = bulletFXLife;
- imp.wasDirected = hasActiveDirector;
- burstTrailFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustFlame_yellow_tiny"));
- burstTrailFX.particleEmitter.emit = true;
- burstTrailFX.transform.parent = (bullet.transform);
- burstTrailFX.transform.localPosition = new Vector3(0, 0, 0);
- burstTrailFX.transform.rotation = bullet.transform.rotation;
- burstTrailFX.particleEmitter.useWorldSpace = false;
- burstTrailFX.particleEmitter.minSize = 0.3f;
- burstTrailFX.particleEmitter.maxSize = 0.3f;
- burstTrailFX.particleEmitter.localVelocity = new Vector3(0, 0, 0);
- burstTrailFX.particleEmitter.minEnergy = 15f;
- burstTrailFX.particleEmitter.maxEnergy = 15f;
- burstTrailFX.particleEmitter.minEmission = 35f;
- burstTrailFX.particleEmitter.maxEmission = 35f;
- burstTrailFX.particleEmitter.angularVelocity = 0.01f;
- burstTrailFX.particleEmitter.rndRotation = false;
- Destroy(burstTrailFX.gameObject, 1.25f);
- this.rigidbody.AddForce(-muzzleFlashLight.forward * (projForce * projKick), ForceMode.Impulse);
- fireBurst = false;
- bulletCoolTimer = rateOfFire + UnityEngine.Random.value;
- if(gunType == 3) Destroy(bullet.gameObject, 4f);
- if (gunType == 2) Destroy(bullet.gameObject, 4f);
- if (gunType == 1) Destroy(bullet.gameObject, 7f);
- if (gunType == 0) Destroy(bullet.gameObject, 95f);
- fireCannonFX.particleEmitter.emit = false;
- this.muzzleFlashLight.GetComponents<Light>().FirstOrDefault().enabled = false;
- return;
- }
- public void checkGunDirector()
- {
- foreach (Part aPart in this.vessel.Parts)
- {
- try
- {
- thisGunDirector = aPart.GetComponentInChildren<gunDirector>();
- }
- catch
- {
- Debug.Log("problem finding gunDirector on this part/vessel!");
- }
- if (thisGunDirector != null)
- {
- if (thisGunDirector.inAction == true)
- {
- hasActiveDirector = true;
- shotPrediction = AnimationCurve.Linear(246f, -3f, 8514f, 12f);
- shotPrediction.AddKey(312f, -2f);
- shotPrediction.AddKey(535f, -1f);
- shotPrediction.AddKey(1252f, 0f);
- shotPrediction.AddKey(2887f, 1f);
- shotPrediction.AddKey(4483f, 2f);
- shotPrediction.AddKey(5598f, 3f);
- shotPrediction.AddKey(6357f, 4f);
- shotPrediction.AddKey(7044f, 5f);
- shotPrediction.AddKey(7826f, 7f);
- shotPrediction.AddKey(8382f, 10f);
- shotPrediction.AddKey(8477f, 11f);
- if (FlightGlobals.fetch.vesselTargetMode != FlightGlobals.VesselTargetModes.None)
- {
- ITargetable target = FlightGlobals.fetch.VesselTarget;
- Vessel targetedVessel = target.GetVessel();
- targetDistance = Vector3.Distance(this.vessel.transform.position, targetedVessel.transform.position);
- if (targetDistance <= 8514f && targetDistance >= 246f)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Use " + shotPrediction.Evaluate(targetDistance) + " Degrees Elevation", 4f, ScreenMessageStyle.UPPER_CENTER));
- }
- else
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Cannot Calculate Solution, Out Of Min/Max Range!", 4f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- }
- else hasActiveDirector = false;
- }
- }
- }
- public void getClosestHostile()
- {
- hostileOne = null;
- hostileTwo = null;
- hostileThree = null;
- targetHostile = null;
- List<Vessel> calledList = IFFList.Instance.IFFRed();
- if (calledList.Contains(this.vessel))
- {
- List<Vessel> lookForBlueTarget = IFFList.Instance.IFFBlue();
- if (lookForBlueTarget.Count > 0)
- {
- foreach (Vessel bVessel in lookForBlueTarget)
- {
- float bTargetDistance = Vector3.Distance(this.vessel.transform.position, bVessel.transform.position);
- if (bTargetDistance <= 3000f && bTargetDistance > 2000f)
- {
- hostileThree = bVessel;
- }
- if (bTargetDistance <= 2000 && bTargetDistance > 1500f)
- {
- hostileTwo = bVessel;
- }
- if (bTargetDistance <= 1500f)
- {
- hostileOne = bVessel;
- }
- foreach (Part p in bVessel.Parts)
- {
- #region antimissile search
- if (p.partName.Contains("PartMissile") && this.isCIWS == true)
- {
- if (p.rigidbody.velocity.magnitude > 200f)
- {
- Vector3 headingDirection = (p.rigidbody.transform.position - turretTransform.position);
- Vector3 forward;
- forward = p.transform.forward;
- if (Vector3.Dot(forward, headingDirection.normalized) > 0f)
- {
- //print("Moving Away");
- }
- else
- {
- hostileClosing = true;
- }
- if (hostileClosing == true)
- {
- float chanceToIntercept = 0.75f;
- float numberRolled = UnityEngine.Random.value * 100f;
- if (chanceToIntercept > numberRolled)
- {
- //print("Intercept roll was " + numberRolled);
- p.explode();
- print("Romfarer missile destroyed by CIWS!");
- }
- }
- }
- }
- #endregion
- }
- }
- }
- if (hostileOne != null)
- {
- targetHostile = hostileOne;
- }
- else if (hostileTwo != null)
- {
- targetHostile = hostileTwo;
- }
- else if (hostileThree != null)
- {
- targetHostile = hostileThree;
- }
- if (hostileOne == null && hostileTwo == null && hostileThree == null)
- {
- targetHostile = null;
- }
- }
- else
- {
- List<Vessel> calledNextList = IFFList.Instance.IFFBlue();
- if (calledNextList.Contains(this.vessel))
- {
- List<Vessel> lookForRedTarget = IFFList.Instance.IFFRed();
- if (lookForRedTarget.Count > 0)
- {
- foreach (Vessel bVessel in lookForRedTarget)
- {
- float bTargetDistance = Vector3.Distance(this.vessel.transform.position, bVessel.transform.position);
- if (bTargetDistance <= 3000f && bTargetDistance > 2000f)
- {
- hostileThree = bVessel;
- }
- if (bTargetDistance <= 2000 && bTargetDistance > 1500f)
- {
- hostileTwo = bVessel;
- }
- if (bTargetDistance <= 1500f)
- {
- hostileOne = bVessel;
- }
- foreach (Part p in bVessel.Parts)
- {
- #region antimissile search
- if (p.partName.Contains("PartMissile"))
- {
- if (p.rigidbody.velocity.magnitude > 200f)
- {
- Vector3 headingDirection = (p.rigidbody.transform.position - turretTransform.position);
- Vector3 forward;
- forward = p.transform.forward;
- if (Vector3.Dot(forward, headingDirection.normalized) > 0f)
- {
- //print("Moving Away");
- }
- else
- {
- hostileClosing = true;
- }
- if (hostileClosing == true)
- {
- float chanceToIntercept = 0.75f;
- float numberRolled = UnityEngine.Random.value * 100f;
- if (chanceToIntercept > numberRolled)
- {
- //print("Intercept roll was " + numberRolled);
- p.explode();
- print("Romfarer missile destroyed by CIWS!");
- }
- }
- }
- }
- #endregion
- }
- }
- }
- if (hostileOne != null)
- {
- targetHostile = hostileOne;
- }
- else if (hostileTwo != null)
- {
- targetHostile = hostileTwo;
- }
- else if (hostileThree != null)
- {
- targetHostile = hostileThree;
- }
- if (hostileOne == null && hostileTwo == null && hostileThree == null)
- {
- targetHostile = null;
- }
- }
- }
- }
- public void autoTracker()
- {
- #region Ball Turret Tracking
- if (turretType == 0 && isTurret == true)
- {
- if (FlightGlobals.fetch.vesselTargetMode != FlightGlobals.VesselTargetModes.None && autoTrackOn == true && guardMode == false)
- {
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.025);
- if (this.vessel == FlightGlobals.ActiveVessel && rotSpdMod > 0.5f)
- {
- float shotGrouping = 0.15f;
- ITargetable target = FlightGlobals.fetch.VesselTarget;
- Vessel v = FlightGlobals.fetch.VesselTarget.GetVessel();
- var lookPos = (target.GetTransform().position - turretTransform.position).normalized;
- var rotation = Quaternion.LookRotation(lookPos, transform.up);
- rotation.x += ((UnityEngine.Random.value - 0.5f) / 100) * shotGrouping;
- rotation.y += ((UnityEngine.Random.value - 0.5f) / 100) * shotGrouping;
- rotation.z += ((UnityEngine.Random.value - 0.5f) / 100) * shotGrouping;
- turretTransform.rotation = Quaternion.Slerp(turretTransform.rotation, rotation, 1f);
- currentTurretLocation = turretTransform.position;
- currentTurretAngle = lookPos;
- if (smartTracking == true)
- {
- foreach (Part p in v.parts)
- {
- foreach (PartModule aModule in p.Modules)
- {
- if (aModule is relayIFF)
- {
- relayIFF checkTargetIFF = aModule.GetComponent<relayIFF>();
- if (p.vessel != base.vessel && checkTargetIFF.setIFF != this.setIFF)
- {
- shotGrouping = 0.25f;
- float leadAmount = 0.4f;
- leadTarget.SetActive(true);
- leadTarget.renderer.enabled = false;
- leadTarget.collider.enabled = false;
- Transform placeLeadTarget = p.vessel.transform;
- leadTarget.transform.rotation = placeLeadTarget.transform.rotation;
- Vector3 changeVector = this.vessel.rigidbody.velocity;
- Vector3 changeVectorNormalized = Vector3.Normalize(changeVector);
- float magnitude = Vector3.Magnitude(changeVector);
- leadTarget.transform.position = p.vessel.transform.position - (changeVectorNormalized * (magnitude * leadAmount));
- lookPos = (leadTarget.transform.position - turretTransform.position).normalized;
- rotation = Quaternion.LookRotation(lookPos, transform.up);
- rotation.x += ((UnityEngine.Random.value - 0.5f) / 40f) * shotGrouping;
- rotation.y += ((UnityEngine.Random.value - 0.5f) / 40f) * shotGrouping;
- rotation.z += ((UnityEngine.Random.value - 0.5f) / 40f) * shotGrouping;
- turretTransform.rotation = rotation;
- currentTurretLocation = turretTransform.position;
- currentTurretAngle = lookPos;
- }
- }
- }
- }
- }
- }
- }
- if (this.vessel != FlightGlobals.ActiveVessel && autoTrackOn == true && guardMode == true) //***********************
- {
- Vector3 BoatPosition = this.vessel.transform.position;
- getClosestHostile();
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.025);
- if (targetHostile != null && rotSpdMod > 0.5f)
- {
- float shotGrouping = 0.2f;
- float leadAmount = guiLead;
- leadMulti = 1f;
- if (Vector3.Distance(BoatPosition, targetHostile.transform.position) > 550f)
- {
- leadMulti = (Vector3.Distance(BoatPosition, targetHostile.transform.position) - 550f) / 625f;
- if (leadMulti > 0f) leadMulti += 1f;
- }
- leadAmount = guiLead * leadMulti;
- float leadSpdSteps = ((targetHostile.rigidbody.velocity.magnitude - 100f) / 100f) * 0.1f;
- leadAmount += leadSpdSteps;
- leadTarget.SetActive(true);
- leadTarget.renderer.enabled = false; //true to debug
- leadTarget.collider.enabled = false;
- Transform placeLeadTarget = targetHostile.transform;
- leadTarget.transform.rotation = placeLeadTarget.transform.rotation;
- Vector3 changeVector = targetHostile.rigidbody.velocity;
- Vector3 changeVectorNormalized = Vector3.Normalize(changeVector);
- float magnitude = Vector3.Magnitude(changeVector);
- leadTarget.transform.position = targetHostile.transform.position + (changeVectorNormalized * (magnitude * leadAmount));
- var lookPos = (leadTarget.transform.position - turretTransform.position).normalized;
- var rotation = Quaternion.LookRotation(lookPos, transform.up);
- if (targetHostile.rigidbody.velocity.magnitude > 400d)
- {
- rotation.x += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 120f) * shotGrouping;
- rotation.y += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 120f) * shotGrouping;
- rotation.z += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 120f) * shotGrouping;
- rateOfFire = origRateOfFire;
- }
- if (targetHostile.rigidbody.velocity.magnitude > 150d && targetHostile.rigidbody.velocity.magnitude <= 400d)
- {
- rotation.x += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 250f) * shotGrouping;
- rotation.y += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 250f) * shotGrouping;
- rotation.z += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 250f) * shotGrouping;
- rateOfFire = origRateOfFire * 1.035f;
- }
- if (targetHostile.rigidbody.velocity.magnitude > 100d && targetHostile.rigidbody.velocity.magnitude <= 150d)
- {
- rotation.x += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 300f) * shotGrouping;
- rotation.y += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 300f) * shotGrouping;
- rotation.z += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 300f) * shotGrouping;
- rateOfFire = origRateOfFire * 1.0875f;
- }
- if (targetHostile.rigidbody.velocity.magnitude > 50d && targetHostile.rigidbody.velocity.magnitude <= 100d)
- {
- rotation.x += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 450f) * shotGrouping;
- rotation.y += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 450f) * shotGrouping;
- rotation.z += (((float)rndNumber.rndDouble(0.0, 1.0) - 0.5f) / 450f) * shotGrouping;
- rateOfFire = origRateOfFire * 1.25f;
- }
- if (targetHostile.rigidbody.velocity.magnitude > 0d && targetHostile.rigidbody.velocity.magnitude <= 50d)
- {
- rateOfFire = origRateOfFire * 2.5f;
- }
- turretTransform.rotation = rotation;
- currentTurretLocation = turretTransform.position;
- currentTurretAngle = lookPos;
- safetyLOS();
- if (randomBurstTimer > 0f)
- {
- randomBurstTimer--;
- fireCannonBurst();
- }
- if (randomBurstTimer <= 0f)
- {
- float randBurstChance = (float)rndNumber.rndRoll(5, 10);
- float rollToBurst = (float)rndNumber.rndRoll(0, 100);
- if (this.isCIWS == true) rollToBurst = 1f;
- if (rollToBurst < randBurstChance)
- {
- randomBurstTimer = (float)rndNumber.rndDouble(60.0, 120.0);
- }
- if (this.isCIWS == true) randomBurstTimer = 1f;
- }
- }
- }
- }
- #endregion
- #region Dual Zone Turret manual control
- if (turretType == 1)
- {
- if (autoTrackOn == false && guardMode == false)
- {
- if (this.vessel == FlightGlobals.ActiveVessel && ctrlTurret == true)
- {
- if (Input.GetKey(KeyCode.Keypad0))
- {
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.045);
- float rotSpeed = 0f;
- if (invertRotation == true)
- {
- rotSpeed = ((14f / this.part.mass) * turretSpeed) * rotSpdMod;
- }
- else if (invertRotation == false)
- {
- rotSpeed = ((-14f / this.part.mass) * turretSpeed) * rotSpdMod;
- }
- turretBodyRotate.transform.Rotate(Vector3.forward * rotSpeed * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.KeypadPeriod))
- {
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.045);
- float rotSpeed = 0f;
- if (invertRotation == true)
- {
- rotSpeed = ((-14f / this.part.mass) * turretSpeed) * rotSpdMod;
- }
- else if (invertRotation == false)
- {
- rotSpeed = ((14f / this.part.mass) * turretSpeed) * rotSpdMod;
- }
- turretBodyRotate.transform.Rotate(Vector3.forward * rotSpeed * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.Keypad5))
- {
- float changeRate;
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.035);
- changeRate = (((-1.75f / (this.part.mass * 0.25f)) * turretSpeed) * rotSpdMod) *Time.deltaTime;
- showTurretElevation -= changeRate;
- turretBarrelElevation.transform.Rotate(0f, 0f, changeRate);
- }
- if (Input.GetKey(KeyCode.Keypad2))
- {
- float changeRate;
- float rotSpdMod = checkElectricity.useElectricCharge(base.part, 0.035);
- changeRate = (((1.75f / (this.part.mass * 0.25f)) * turretSpeed) * rotSpdMod) * Time.deltaTime;
- showTurretElevation -= changeRate;
- turretBarrelElevation.transform.Rotate(0f, 0f, changeRate);
- }
- }
- }
- }
- #endregion
- }
- public void safetyLOS()
- {
- float range = 3000f;
- Vessel vesselHit;
- vesselHit = null;
- fireOverride = false;
- tripOverride = false;
- rayLOS = new Ray(currentTurretLocation, currentTurretAngle);
- if (Physics.Raycast(rayLOS.origin, rayLOS.direction, out hitLOS, range))
- {
- if (hitLOS.collider.attachedRigidbody != null)
- {
- Part hitPart = hitLOS.collider.attachedRigidbody.GetComponent<Part>();
- if (hitPart != null)
- {
- vesselHit = hitPart.vessel;
- if (vesselHit != null)
- {
- List<Vessel> calledList = IFFList.Instance.IFFBlue();
- List<Vessel> calledNextList = IFFList.Instance.IFFRed();
- if (calledList.Contains(this.vessel) && calledList.Contains(vesselHit) || calledNextList.Contains(this.vessel) && calledNextList.Contains(vesselHit) || this.vessel == vesselHit)
- {
- tripOverride = true;
- }
- }
- }
- }
- if (hitLOS.collider.gameObject.layer == 15) fireOverride = true;
- if (tripOverride == true)
- {
- fireOverride = true;
- }
- }
- }
- }
- public class impact : MonoBehaviour
- {
- public float collisionForce;
- public float useHardness;
- public float useWarheadType;
- public float useProjPenetrate;
- public bool doItOnce = true;
- public float skinWidth = 0.05f;
- private float minimumExtent;
- private float partialExtent;
- private float sqrMinimumExtent;
- private float lastGoodVelocity;
- public bool wasDirected = false;
- public Rigidbody rb;
- public GameObject bulletHoleInstance;
- public float bulletHoleChance;
- public float bulletHoleTime;
- public bool spawnOneFX = true;
- public Vector3 previousPosition;
- public Vector3 thisWayUp;
- public RaycastHit sendLastGoodRaycastHit;
- public float origDrag;
- public double partAltitude;
- void Awake()
- {
- rb = this.rigidbody;
- previousPosition = rb.position;
- minimumExtent = Mathf.Min(Mathf.Min(collider.bounds.extents.x, collider.bounds.extents.y), collider.bounds.extents.z);
- partialExtent = minimumExtent * (1.0f - skinWidth);
- sqrMinimumExtent = minimumExtent * minimumExtent;
- }
- public void FixedUpdate()
- {
- thisWayUp = (this.transform.position - FlightGlobals.ActiveVessel.mainBody.position).normalized;
- if (this.gameObject != null)
- {
- partAltitude = Vector3.Distance(this.rigidbody.transform.position, FlightGlobals.ActiveVessel.mainBody.position) - (float)FlightGlobals.ActiveVessel.mainBody.Radius;
- Vector3 movementThisStep = rb.position - previousPosition;
- float movementSqrMagnitude = movementThisStep.sqrMagnitude;
- if (movementSqrMagnitude > sqrMinimumExtent)
- {
- float movementMagnitude = Mathf.Sqrt(movementSqrMagnitude);
- RaycastHit hitInfo;
- #region bullet hole trial code
- //print(hitInfo.collider.gameObject.layer);
- //if (spawnOneFX == true) //only make one fx
- //{
- // if (hitInfo.collider.gameObject.layer != 15)
- // {
- // #region Place a bullet hole gameobject where the raycast hit.
- // try
- // {
- // bulletHoleInstance = GameDatabase.Instance.GetModel("IDSkillfulR1/Parts/bulletDecal/model");
- // }
- // catch
- // {
- // Debug.Log("Problem finding bullet hole decal!");
- // }
- // if (bulletHoleInstance != null)
- // {
- // //print("Inside spawning bullet hole!");
- // float bulletHoleScale = (float)Math.Sqrt(rb.mass) * 3f;
- // //print("step1");
- // GameObject newBulletHit = (GameObject)GameObject.Instantiate(bulletHoleInstance, hitInfo.point + (hitInfo.normal * 0.001f * (float)rndNumber.rndDouble(0.01, 0.001)), Quaternion.LookRotation(-hitInfo.normal));
- // //print("step2");
- // newBulletHit.transform.parent = hitInfo.collider.transform;
- // //print("step3");
- // newBulletHit.transform.localScale = new Vector3(bulletHoleScale, bulletHoleScale, 0.00001f);
- // //print("step4");
- // newBulletHit.SetActive(true);
- // //print("step5");
- // GameObject.Destroy(newBulletHit, bulletHoleTime); //set bulletFXLife in gun cfg to affect this bulletHoleTime - default is 10 seconds
- // spawnOneFX = false;
- // }
- // #endregion
- // Destroy(this.gameObject, 0.5f);
- // }
- //}
- #endregion
- if (Physics.Raycast(previousPosition, movementThisStep, out hitInfo, movementMagnitude, 1))
- {
- rb.position = hitInfo.point - (movementThisStep / movementMagnitude) * partialExtent;
- }
- }
- if (this.partAltitude < -3.0)
- {
- //print("Projectile Hit the water!");
- if (wasDirected == true)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Water impact at range: " + Vector3.Distance(rb.transform.position, FlightGlobals.ActiveVessel.transform.position), 4f, ScreenMessageStyle.UPPER_CENTER));
- //print("Water impact at range: " + Vector3.Distance(rb.transform.position, FlightGlobals.ActiveVessel.transform.position));
- }
- if (rb.mass >= 0.01f)
- {
- GameObject fxSplashInstance = new GameObject();
- try
- {
- fxSplashInstance = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/largeSplash/model");
- }
- catch
- {
- print("Problem locating largeSplash");
- }
- if (fxSplashInstance != null)
- {
- fxSplashInstance.transform.position = this.transform.position;
- fxSplashInstance.transform.LookAt(FlightGlobals.ActiveVessel.mainBody.transform);
- fxSplashInstance.SetActive(true);
- endFx fxSplashEnds = fxSplashInstance.AddComponent<endFx>();
- fxSplashEnds.endTime = 2f;
- Destroy(fxSplashInstance, 8f * rb.mass);
- }
- }
- FXMonger.Splash(this.transform.position, (this.rigidbody.velocity.magnitude * (this.rigidbody.mass * 100f)));
- Destroy(this.gameObject);
- }
- if (rb.velocity.magnitude < 50f)
- {
- Destroy(this.gameObject, 0.0f);
- }
- previousPosition = rb.position;
- lastGoodVelocity = rb.velocity.magnitude;
- }
- }
- public void OnTriggerEnter(Collider Collision)
- {
- if (Collision.gameObject.layer == 15)
- {
- if (wasDirected == true)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Shot impacted ground/structure at range: " + Vector3.Distance(rb.transform.position, FlightGlobals.ActiveVessel.transform.position), 4f, ScreenMessageStyle.UPPER_CENTER));
- //print("Shot impacted ground/structure at range: " + Vector3.Distance(rb.transform.position, FlightGlobals.ActiveVessel.transform.position));
- }
- if (useWarheadType == 1f || useWarheadType == 2f) FXMonger.Explode(FlightGlobals.ActiveVessel.rootPart, this.transform.position, rb.mass);
- terrainHit();
- }
- }
- public static void doShrapnel(GameObject thisProjectile, float projMass, Vector3 projSpeed, float explodePower)
- {
- int shrapLimit = 2;
- #region Shrapnel Limit
- if (projMass < 0.25f)
- {
- shrapLimit = 4;
- }
- if (projMass >= 0.25f && projMass < 0.5f)
- {
- shrapLimit = rndNumber.rndRoll(4, 8);
- }
- if (projMass >= 0.5f && projMass < 1f)
- {
- shrapLimit = rndNumber.rndRoll(5, 16);
- }
- if (projMass >= 1f && projMass < 4f)
- {
- shrapLimit = rndNumber.rndRoll(6, 24);
- }
- if (projMass >= 4f && projMass < 10f)
- {
- shrapLimit = rndNumber.rndRoll(7, 32);
- }
- #endregion
- int shrapnel = rndNumber.rndRoll(1, shrapLimit);
- int fragCache = shrapnel;
- GameObject[] exFrag = new GameObject[fragCache];
- for (int i = 0; i < exFrag.Length; i++)
- {
- exFrag[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
- exFrag[i].SetActive(true);
- exFrag[i].renderer.enabled = false;
- exFrag[i].transform.localScale = new Vector3(0.25f, 0.25f, 0.25f);
- exFrag[i].transform.position = thisProjectile.transform.position + UnityEngine.Random.insideUnitSphere * (explodePower * 0.225f);
- Vector3 randomDirection = new Vector3(rndNumber.rndRoll(-359, 359), rndNumber.rndRoll(-359, 359), rndNumber.rndRoll(-359, 359));
- exFrag[i].transform.Rotate(randomDirection);
- Rigidbody rb = exFrag[i].AddComponent<Rigidbody>();
- rb.detectCollisions = true;
- rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
- rb.mass = (projMass / shrapnel);
- rb.drag = rndNumber.rndFloat(0.1f, 0.3f);
- rb.velocity = projSpeed * 0.75f;
- setColliderStateInChildren(exFrag[i], true);
- fragImpact fI = exFrag[i].AddComponent<fragImpact>();
- fI.fragWarheadType = 0f;
- fI.fragHardness = 320f;
- Destroy(exFrag[i].gameObject, 5f);
- }
- }
- public static void setColliderStateInChildren(GameObject rootObject, bool isTrigger)
- {
- Collider[] colliders = rootObject.GetComponentsInChildren<Collider>(true);
- for (int i = 0; i < colliders.Length; i++)
- {
- colliders[i].isTrigger = isTrigger;
- colliders[i].enabled = true;
- }
- }
- public void terrainHit()
- {
- GameObject explosion = Part.Instantiate(UnityEngine.Resources.Load("Effects/fx_exhaustSparks_yellow")) as GameObject;
- explosion.transform.localEulerAngles = Vector3.zero;
- explosion.transform.localPosition = new Vector3(0, 0, 0);
- explosion.transform.position = this.transform.position;
- ParticleEmitter emitter = explosion.particleEmitter;
- emitter.emit = false;
- emitter.minSize = (rb.mass * 0.5f) + 0.35f;
- emitter.maxSize = (rb.mass * 2f) + 1f;
- emitter.minEnergy = (rb.mass * (rb.velocity.magnitude * 0.0025f)) + 1.2f;
- emitter.maxEnergy = (rb.mass * (rb.velocity.magnitude *0.005f)) + 1.5f;
- emitter.rndVelocity = Vector3.one * (float)rndNumber.rndDouble(0.01, 1.0);
- emitter.localVelocity = Vector3.zero;
- emitter.useWorldSpace = true;
- ParticleAnimator emitterAnimator = emitter.GetComponent<ParticleAnimator>();
- emitterAnimator.sizeGrow = 0.0035f;
- Color[] emitterColors = emitterAnimator.colorAnimation;
- emitterColors[0] = new Color(0.5f, 0.45f, 0.18f, 0.95f);
- emitterColors[1] = new Color(0.8f, 0.8f, 0.8f, 1f);
- emitterColors[2] = new Color(0.85f, 0.1f, 0.1f, 0.7f);
- emitterColors[3] = new Color(0.5f, 0.5f, 0.5f, 0.5f);
- emitterColors[4] = new Color(0f, 0f, 0f, 0.25f);
- emitterAnimator.colorAnimation = emitterColors;
- emitter.Emit(8);
- if (useWarheadType == 1f && rb.mass >= 0.01f)
- {
- float explosionPower = rigidbody.mass * 500f;
- float blastRadius = explosionPower * 0.25f;
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- float blastDistance = Vector3.Distance(v.transform.position, this.transform.position);
- if (blastDistance < blastRadius)
- {
- try
- {
- v.GoOffRails();
- }
- catch
- {
- print("Something is wrong with making the vessel offrails");
- }
- FXMonger.Explode(v.rootPart, v.transform.position, 0.9f / blastDistance);
- v.rigidbody.AddForceAtPosition(Vector3.forward * (explosionPower / (blastDistance * 0.25f)), v.transform.position, ForceMode.Impulse);
- doShrapnel(this.gameObject, rb.mass, rb.velocity, explosionPower);
- }
- }
- }
- if (useWarheadType == 2f && rb.mass >= 0.01f)
- {
- //print("this is an Incendiary hit!");
- GameObject fxFireInstance = new GameObject();
- try
- {
- fxFireInstance = GameDatabase.Instance.GetModel("IDSkillfulR1/Effects/largeGFire/model");
- }
- catch
- {
- print("Problem locating fireFX");
- }
- if (fxFireInstance != null)
- {
- fxFireInstance.SetActive(true);
- fxFireInstance.transform.position = this.transform.position;
- fxFireInstance.transform.LookAt(FlightGlobals.ActiveVessel.mainBody.transform);
- terrainBurner tB = fxFireInstance.AddComponent<terrainBurner>();
- tB.throwsHeat = 100f;
- tB.heatRange = rb.mass * 80f;
- Destroy(fxFireInstance, 300f * (float)rndNumber.rndDouble(0.75, 2.5));
- }
- }
- Destroy(this.gameObject);
- }
- }
- public class gunDirector : PartModule
- {
- public float lastShotDistance = 0f;//maybe use these later.
- public float lastShotElevation = 0f;
- [KSPField(isPersistant=true,guiActive=true)]
- public bool inAction = true;
- public void FixedUpdate()
- {
- //something here
- }
- public void doRangeMessage(float rangeMsg)
- {
- }
- public void ApplyDamage(float damageState)
- {
- float chanceBroken = rndNumber.rndRoll(0, 100);
- if (chanceBroken < 5f)
- {
- inAction = false;
- }
- if (damageState < 1f)
- {
- //this.origRange *= damageState;
- }
- if (damageState == 1f)
- {
- inAction = true;
- }
- }
- }
- //class turretControllerGUI
- //{
- // public Rect windowRect = new Rect(500f, 200f, 150f, 30f);
- // public int windowID;
- // public Vector2 buttonSize = new Vector2(30f, 30f);
- // public float padding = 8f;
- // public Rect drawPosition = new Rect(0f, 0f, 30f, 30f);
- // private GUIStyle buttonPassive;
- // private GUIStyle buttonActive;
- // private bool stylesCreated = false;
- // public bool turretSummonsYou = false;
- // private Color faintBlack = new Color(0f, 0f, 0f, 0.1f);
- // private Color opaqueBlack = new Color(0f, 0f, 0f, 1f);
- // private void createStyles()
- // {
- // buttonPassive = new GUIStyle(GUI.skin.button);
- // buttonActive = new GUIStyle(GUI.skin.button);
- // buttonPassive.normal.textColor = Color.gray;
- // buttonActive.normal.textColor = Color.white;
- // buttonPassive.normal.background = new Texture2D(1, 1);
- // buttonPassive.normal.background.SetPixel(0, 0, faintBlack);
- // buttonPassive.normal.background.Apply();
- // buttonActive.normal.background = new Texture2D(1, 1);
- // buttonActive.normal.background.SetPixel(0, 0, opaqueBlack);
- // buttonActive.normal.background.Apply();
- // buttonPassive.padding = new RectOffset(2, 2, 2, 2);
- // buttonActive.padding = new RectOffset(2, 2, 2, 2);
- // stylesCreated = true;
- // }
- // private GUIStyle getButtonStyle(KeyCode key)
- // {
- // if (Input.GetKey(key))
- // return buttonActive;
- // else
- // return buttonPassive;
- // }
- // private GUIStyle getButtonStyle(bool state)
- // {
- // if (state)
- // return buttonActive;
- // else
- // return buttonPassive;
- // }
- // private Rect longButtonRect(float length)
- // {
- // return new Rect(drawPosition.x, drawPosition.y, buttonSize.x * length, buttonSize.y);
- // }
- // public turretControllerGUI()
- // {
- // windowID = 13434;
- // }
- // private void nextButtonPos()
- // {
- // drawPosition.x += buttonSize.x + padding;
- // }
- // private void newLine(float x)
- // {
- // drawPosition.x = x;
- // drawPosition.y += buttonSize.y + padding;
- // }
- // public void drawWindow(int ID)
- // {
- // GUI.DragWindow();
- // }
- // public void OnGUI()
- // {
- // if (turretSummonsYou == true)
- // {
- // if (!stylesCreated)
- // createStyles();
- // windowRect = GUI.Window(windowID, windowRect, drawWindow, "Input Visualizer", buttonActive);
- // float letterKeysXpos = windowRect.x + buttonSize.x * 2 + padding * 2;
- // drawPosition.x = letterKeysXpos;
- // drawPosition.y = windowRect.y + windowRect.height + padding;
- // GUI.Button(drawPosition, "Q", getButtonStyle(KeyCode.Q));
- // nextButtonPos();
- // GUI.Button(drawPosition, "W", getButtonStyle(KeyCode.W));
- // nextButtonPos();
- // GUI.Button(drawPosition, "E", getButtonStyle(KeyCode.E));
- // newLine(letterKeysXpos);
- // GUI.Button(drawPosition, "A", getButtonStyle(KeyCode.A));
- // nextButtonPos();
- // GUI.Button(drawPosition, "S", getButtonStyle(KeyCode.S));
- // nextButtonPos();
- // GUI.Button(drawPosition, "D", getButtonStyle(KeyCode.D));
- // newLine(letterKeysXpos);
- // GUI.Button(drawPosition, "Z", getButtonStyle(KeyCode.Z));
- // nextButtonPos();
- // GUI.Button(drawPosition, "X", getButtonStyle(KeyCode.X));
- // nextButtonPos();
- // GUI.Button(drawPosition, "C", getButtonStyle(KeyCode.C));
- // newLine(letterKeysXpos);
- // drawPosition.x = windowRect.x;
- // drawPosition.y = windowRect.y + windowRect.height + padding * 2 + buttonSize.y;
- // GUI.Button(longButtonRect(2), "Caps", getButtonStyle(KeyCode.CapsLock));
- // drawPosition.y += buttonSize.y + padding;
- // GUI.Button(longButtonRect(2), "Shift", getButtonStyle(KeyCode.LeftShift));
- // drawPosition.y += buttonSize.y + padding;
- // GUI.Button(longButtonRect(2), "Ctrl", getButtonStyle(KeyCode.LeftControl));
- // }
- // }
- //}
- public class checkElectricity : MonoBehaviour
- {
- public static float useElectricCharge(Part basePart, double useCharge)
- {
- double getCharge;
- getCharge = basePart.RequestResource("ElectricCharge", useCharge);
- if (getCharge > 0f)
- {
- double resourceReceived = getCharge / useCharge;
- float finalUsedOutput = Mathf.Clamp((float)resourceReceived, 0f, 1f);
- return finalUsedOutput;
- }
- else
- {
- return 0.0f;
- }
- }
- }
- public class endFx : MonoBehaviour
- {
- public GameObject thisObject;
- public float endTime = 2f;
- KSPParticleEmitter[] thisKPE;
- public void Start()
- {
- thisObject = this.gameObject;
- Invoke("StopEmitter", endTime);
- }
- public void StopEmitter()
- {
- thisKPE = base.GetComponentsInChildren<KSPParticleEmitter>();
- if (thisKPE != null)
- {
- //print("Number of KSPParticleEmitters: " + thisKPE.Length);
- if (thisKPE.Length > 1)
- {
- for (int i = 0; i < thisKPE.Length; i++)
- {
- thisKPE[i].emit = false;
- }
- }
- }
- //print("Stopped emitting after " + endTime + " seconds!");
- }
- }
- ****end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement