private void Fire() { if(BDArmorySettings.GameIsPaused) { if(audioSource.isPlaying) { audioSource.Stop(); } return; } float timeGap = (60/roundsPerMinute) * TimeWarp.CurrentRate; if(Time.time-timeFired > timeGap && !isOverheated && !pointingAtSelf) { bool effectsShot = false; //Transform[] fireTransforms = part.FindModelTransforms("fireTransform"); for(int i = 0; i < fireTransforms.Length; i++) { if(!Misc.CheckMouseIsOnGui() && WMgrAuthorized() && (BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount)>0)) { Transform fireTransform = fireTransforms[i]; spinningDown = false; //recoil if(hasRecoil) { gameObject.rigidbody.AddForceAtPosition((-fireTransform.forward) * (bulletVelocity*bulletMass), fireTransform.position, ForceMode.Impulse); } if(!effectsShot) { //sound if(oneShotSound) { audioSource.Stop(); audioSource.PlayOneShot(fireSound); } else { wasFiring = true; if(!audioSource.isPlaying) { audioSource.clip = fireSound; audioSource.loop = false; audioSource.time = 0; audioSource.Play(); } else { if (audioSource.time >= fireSound.length) { audioSource.time = soundRepeatTime; } } } //animation if(hasFireAnimation) { float unclampedSpeed = (roundsPerMinute*fireState.length)/60; fireAnimSpeed = Mathf.Clamp (unclampedSpeed, 1, 20); fireState.enabled = true; if(unclampedSpeed == fireAnimSpeed) { fireState.normalizedTime = 0; } fireState.speed = fireAnimSpeed; fireState.normalizedTime = Mathf.Repeat(fireState.normalizedTime, 1); } //muzzle flash foreach(Transform mtf in part.FindModelTransforms("muzzleTransform")) { KSPParticleEmitter pEmitter = mtf.gameObject.GetComponent<KSPParticleEmitter>(); if(!pEmitter.useWorldSpace || oneShotWorldParticles) { pEmitter.Emit(); } } foreach(var gpe in gaplessEmitters) { gpe.EmitParticles(); } //shell ejection if(BDArmorySettings.EJECT_SHELLS) { for(int e = 0; e < shellEjectTransforms.Length; e++) { Transform sTf = shellEjectTransforms[e]; //GameObject ejectedShell = (GameObject) Instantiate(GameDatabase.Instance.GetModel("BDArmory/Models/shell/model"), sTf.position + (part.rb.velocity*Time.fixedDeltaTime), sTf.rotation); GameObject ejectedShell = shellPool.GetPooledObject(); ejectedShell.transform.position = sTf.position;//+(part.rb.velocity*TimeWarp.fixedDeltaTime); ejectedShell.transform.rotation = sTf.rotation; ejectedShell.transform.localScale = Vector3.one * shellScale; ShellCasing shellComponent = ejectedShell.GetComponent<ShellCasing>(); shellComponent.initialV = part.rb.velocity; ejectedShell.SetActive(true); } } effectsShot = true; } //firing bullet GameObject firedBullet = bulletPool.GetPooledObject(); PooledBullet pBullet = firedBullet.GetComponent<PooledBullet>(); firedBullet.transform.position = fireTransform.position; pBullet.mass = bulletMass; pBullet.ballisticCoefficient = bulletBallisticCoefficient; pBullet.flightTimeElapsed = 0; timeFired = Time.time; //Vector3 firedVelocity = fireTransform.rotation * new Vector3(randomZ,randomY,bulletVelocity).normalized * bulletVelocity; Vector3 firedVelocity = VectorUtils.WeightedDirectionDeviation(fireTransform.forward, maxDeviation) * bulletVelocity; //firedBullet.transform.position -= firedVelocity * Time.fixedDeltaTime; firedBullet.transform.position += part.rb.velocity * Time.fixedDeltaTime; pBullet.currentVelocity = part.rb.velocity + firedVelocity; pBullet.initialSpeed = bulletVelocity; pBullet.sourceVessel = this.vessel; pBullet.bulletTexturePath = bulletTexturePath; pBullet.projectileColor = projectileColorC; pBullet.startColor = startColorC; pBullet.fadeColor = fadeColor; tracerIntervalCounter++; if(tracerIntervalCounter > tracerInterval) { tracerIntervalCounter = 0; pBullet.tracerStartWidth = tracerStartWidth; pBullet.tracerEndWidth = tracerEndWidth; } else { pBullet.tracerStartWidth = nonTracerWidth; pBullet.tracerEndWidth = nonTracerWidth; pBullet.startColor.a *= 0.5f; pBullet.projectileColor.a *= 0.5f; } pBullet.tracerLength = tracerLength; pBullet.tracerDeltaFactor = tracerDeltaFactor; pBullet.tracerLuminance = tracerLuminance; pBullet.bulletDrop = bulletDrop; if(weaponType == "cannon") { pBullet.bulletType = PooledBullet.PooledBulletTypes.Explosive; pBullet.explModelPath = explModelPath; pBullet.explSoundPath = explSoundPath; pBullet.blastPower = cannonShellPower; pBullet.radius = cannonShellRadius; pBullet.airDetonation = airDetonation; pBullet.detonationRange = detonationRange; } else { pBullet.bulletType = PooledBullet.PooledBulletTypes.Standard; pBullet.airDetonation = false; } switch(bulletDragType) { case BulletDragTypes.None: pBullet.dragType = PooledBullet.BulletDragTypes.None; break; case BulletDragTypes.AnalyticEstimate: pBullet.dragType = PooledBullet.BulletDragTypes.AnalyticEstimate; break; case BulletDragTypes.NumericalIntegration: pBullet.dragType = PooledBullet.BulletDragTypes.NumericalIntegration; break; } pBullet.gameObject.SetActive(true); //heat heat += heatPerShot; } else { spinningDown = true; if(!oneShotSound && wasFiring) { audioSource.Stop (); wasFiring = false; audioSource2.PlayOneShot(overheatSound); } } } } else { spinningDown = true; } }
private bool FireLaser() { float maxDistance = BDArmorySettings.PHYSICS_RANGE; if(BDArmorySettings.PHYSICS_RANGE == 0) maxDistance = 2500; float chargeAmount = requestResourceAmount * TimeWarp.fixedDeltaTime; if(!pointingAtSelf && !Misc.CheckMouseIsOnGui() && WMgrAuthorized() && !isOverheated && (part.RequestResource(ammoName, chargeAmount)>=chargeAmount || BDArmorySettings.INFINITE_AMMO)) { if(!audioSource.isPlaying) { audioSource.PlayOneShot (chargeSound); audioSource.Play(); audioSource.loop = true; } for(int i = 0; i < fireTransforms.Length; i++) { Transform tf = fireTransforms[i]; LineRenderer lr = laserRenderers[i]; //lr.SetPosition(0, tf.position + (part.rb.velocity*Time.fixedDeltaTime)); Vector3 rayDirection = tf.forward; Vector3 targetDirection = Vector3.zero; //autoTrack enhancer Vector3 targetDirectionLR = tf.forward; Vector3 physStepFix = Vector3.zero; if(legacyTargetVessel!=null && legacyTargetVessel.loaded) { physStepFix = legacyTargetVessel.rb_velocity*Time.fixedDeltaTime; targetDirection = (legacyTargetVessel.CoM+physStepFix) - tf.position; if(Vector3.Angle(rayDirection, targetDirection) < 1) { rayDirection = targetDirection; targetDirectionLR = legacyTargetVessel.CoM+(2*physStepFix) - tf.position; } } else if(slaved) { physStepFix = (targetVelocity)*Time.fixedDeltaTime; targetDirection = (targetPosition+physStepFix) - tf.position; rayDirection = targetDirection; targetDirectionLR = targetDirection + physStepFix; } Ray ray = new Ray(tf.position, rayDirection); lr.useWorldSpace = false; lr.SetPosition(0, Vector3.zero); RaycastHit hit; if(Physics.Raycast(ray, out hit, maxDistance, 557057)) { lr.useWorldSpace = true; laserPoint = hit.point + physStepFix; //lr.SetPosition(1, lr.transform.InverseTransformPoint(laserPoint)); lr.SetPosition(0, tf.position+(part.rb.velocity*Time.fixedDeltaTime)); lr.SetPosition(1, laserPoint); if(Time.time-timeFired > 6/120 && BDArmorySettings.BULLET_HITS) { BulletHitFX.CreateBulletHit(hit.point, hit.normal, false); } Part p = hit.collider.gameObject.GetComponentInParent<Part>(); if(p && p.vessel && p.vessel!=this.vessel) { float distance = hit.distance; //Scales down the damage based on the increased surface area of the area being hit by the laser. Think flashlight on a wall. p.temperature += laserDamage/(1+Mathf.PI*Mathf.Pow(tanAngle*distance,2))*TimeWarp.fixedDeltaTime; if(BDArmorySettings.INSTAKILL) p.temperature += p.maxTemp; } } else { laserPoint = lr.transform.InverseTransformPoint((targetDirectionLR*maxDistance)+tf.position); lr.SetPosition(1, laserPoint); } } heat += heatPerShot * TimeWarp.CurrentRate; return true; } else { return false; } }
public override void OnStart (StartState state) { base.OnStart (state); ParseWeaponType(); ParseBulletDragType(); bulletBallisticCoefficient = bulletMass / bulletDragArea * 1000; //1000 to convert from tonnes to kilograms if(shortName == string.Empty) { shortName = part.partInfo.title; } foreach(var emitter in part.FindModelComponents<KSPParticleEmitter>()) { emitter.emit = false; } if(airDetonation) { var detRange = (UI_FloatRange)Fields["defaultDetonationRange"].uiControlEditor; detRange.maxValue = maxAirDetonationRange; } else { Fields["defaultDetonationRange"].guiActive = false; Fields["defaultDetonationRange"].guiActiveEditor = false; } if(HighLogic.LoadedSceneIsFlight) { if(eWeaponType != WeaponTypes.Laser) { if(bulletPool == null) { SetupBulletPool(); } if(shellPool == null) { SetupShellPool(); } } //setup transforms fireTransforms = part.FindModelTransforms(fireTransformName); shellEjectTransforms = part.FindModelTransforms(shellEjectTransformName); //setup emitters foreach(var pe in part.FindModelComponents<KSPParticleEmitter>()) { pe.maxSize *= part.rescaleFactor; pe.minSize *= part.rescaleFactor; pe.shape3D *= part.rescaleFactor; pe.shape2D *= part.rescaleFactor; pe.shape1D *= part.rescaleFactor; if(pe.useWorldSpace && !oneShotWorldParticles) { BDAGaplessParticleEmitter gpe = pe.gameObject.AddComponent<BDAGaplessParticleEmitter>(); gpe.part = part; gaplessEmitters.Add(gpe); } } //setup projectile colors projectileColorC = Misc.ParseColor255(projectileColor); startColorC = Misc.ParseColor255(startColor); //init and zero points targetPosition = Vector3.zero; pointingAtPosition = Vector3.zero; bulletPrediction = Vector3.zero; //setup audio SetupAudio(); //laser setup if(eWeaponType == WeaponTypes.Laser) { SetupLaserSpecifics(); } } else if(HighLogic.LoadedSceneIsEditor) { fireTransforms = part.FindModelTransforms(fireTransformName); } //turret setup foreach(var turr in part.FindModulesImplementing<ModuleTurret>()) { if(turr.turretID == turretID) { turret = turr; break; } } if(!turret) { Fields["onlyFireInRange"].guiActive = false; Fields["onlyFireInRange"].guiActiveEditor = false; } //setup animations if(hasDeployAnim) { deployState = Misc.SetUpSingleAnimation(deployAnimName, this.part); deployState.normalizedTime = 0; deployState.speed = 0; deployState.enabled = true; } if(hasFireAnimation) { fireState = Misc.SetUpSingleAnimation (fireAnimName, this.part); fireState.enabled = false; } BDArmorySettings.OnVolumeChange += UpdateVolume; }
void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) { if (!startedLanded) { targetPosition = FlightPosition(targetPosition, minAltitude); } Vector3d srfVel = vessel.srf_velocity; if (srfVel != Vector3d.zero) { velocityTransform.rotation = Quaternion.LookRotation(srfVel, -vesselTransform.forward); } velocityTransform.rotation = Quaternion.AngleAxis(90, velocityTransform.right) * velocityTransform.rotation; Vector3 localAngVel = vessel.angularVelocity; if (steerMode == SteerModes.NormalFlight) { float angleToTarget = Vector3.Angle(targetPosition - vesselTransform.position, vesselTransform.up); Vector3 dampedDirection = Vector3.RotateTowards(vesselTransform.up, targetPosition - vesselTransform.position, (angleToTarget / 2) * Mathf.Deg2Rad, 0).normalized; targetPosition = vesselTransform.position + (500 * dampedDirection); } if (BDArmorySettings.DRAW_DEBUG_LINES) { flyingToPosition = targetPosition; } Vector3 targetDirection; Vector3 targetDirectionYaw; float yawError; float pitchError; float postYawFactor; float postPitchFactor; if (steerMode == SteerModes.NormalFlight) { targetDirection = velocityTransform.InverseTransformDirection(targetPosition - velocityTransform.position).normalized; targetDirection = Vector3.RotateTowards(Vector3.up, targetDirection, 45 * Mathf.Deg2Rad, 0); targetDirectionYaw = vesselTransform.InverseTransformDirection(vessel.srf_velocity).normalized; targetDirectionYaw = Vector3.RotateTowards(Vector3.up, targetDirectionYaw, 45 * Mathf.Deg2Rad, 0); postYawFactor = 1; postPitchFactor = 1; } else //(steerMode == SteerModes.Aiming) { targetDirection = vesselTransform.InverseTransformDirection(targetPosition - vesselTransform.position).normalized; targetDirection = Vector3.RotateTowards(Vector3.up, targetDirection, 45 * Mathf.Deg2Rad, 0); targetDirectionYaw = targetDirection; if (command == PilotCommands.Follow) { postYawFactor = 1.5f; postPitchFactor = 1f; } else { postYawFactor = 1.6f; postPitchFactor = 2.4f; } } pitchError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirection, Vector3.right), Vector3.back); yawError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirectionYaw, Vector3.forward), Vector3.right); float finalMaxSteer = threatLevel * maxSteer; float steerPitch = (postPitchFactor * 0.015f * steerMult * pitchError) - (postPitchFactor * steerDamping * -localAngVel.x); float steerYaw = (postYawFactor * 0.022f * steerMult * yawError) - (postPitchFactor * steerDamping * -localAngVel.z); s.yaw = Mathf.Clamp(steerYaw, -finalMaxSteer, finalMaxSteer); s.pitch = Mathf.Clamp(steerPitch, Mathf.Min(-finalMaxSteer, -0.2f), finalMaxSteer); //roll Vector3 currentRoll = -vesselTransform.forward; Vector3 rollTarget; if (steerMode == SteerModes.Aiming || Vector3.Angle(vesselTransform.up, targetPosition - vesselTransform.position) > 2) { rollTarget = (targetPosition + ((steerMode == SteerModes.Aiming ? 10 : 45f) * upDirection)) - vesselTransform.position; } else { rollTarget = upDirection; } if (command == PilotCommands.Follow && useRollHint) { rollTarget = -commandLeader.vessel.ReferenceTransform.forward; } rollTarget = Vector3.ProjectOnPlane(rollTarget, vesselTransform.up); float rollError = Misc.SignedAngle(currentRoll, rollTarget, vesselTransform.right); debugString += "\nRoll offset: " + rollError; float steerRoll = (steerMult * 0.0015f * rollError); debugString += "\nSteerRoll: " + steerRoll; float rollDamping = (.10f * steerDamping * -localAngVel.y); steerRoll -= rollDamping; debugString += "\nRollDamping: " + rollDamping; float roll = Mathf.Clamp(steerRoll, -maxSteer, maxSteer); s.roll = roll; // }