private static bool IsInFOV(this IController controller, ITargetable target) { var heading = Vector3.Normalize(target.Transform.position - controller.Transform.position); var dot = Vector3.Dot(controller.Transform.forward, heading); var degrees = Mathf.Rad2Deg * Mathf.Acos(dot); return degrees < controller.Angle; }
public override void OnUpdate() { if (!JUtil.VesselIsInIVA(vessel)) { wasOutsideOnPreviousFrame = true; return; } // Restoring target. if (needsRestoring && target != null && FlightGlobals.fetch.VesselTarget == null) { FlightGlobals.fetch.SetVesselTarget(target); } else { target = FlightGlobals.fetch.VesselTarget; } needsRestoring = false; // Restoring reference. if (wasOutsideOnPreviousFrame && referencePart != null && referencePart.vessel == vessel && vessel.GetReferenceTransformPart() == part) { referencePart.MakeReferencePart(); } if (!GameSettings.CAMERA_NEXT.GetKey()) { referencePart = vessel.GetReferenceTransformPart(); wasOutsideOnPreviousFrame = false; } else { wasOutsideOnPreviousFrame = true; } }
public override void Update(float dt) { if (currentEnemy == null) { List<ITargetable> targets = map.GetTargetsInRange(position, info.range); for (int x = 0; x < targets.Count; x++) { if (targets[x] == this) continue; if (targets[x].GetTeam() != GetTeam()) { currentEnemy = targets[x]; } } } else { if (CanAttack(currentEnemy)) { atkCooldown = 1.0f / info.attackSpeed; map.Attacks.Add(new Attack(map, DamageType.Physical, info.attack, info.armorPen, position,this, currentEnemy, 60)); } if (currentEnemy.IsDead() || (currentEnemy.GetPosition()-GetPosition()).LengthSquared() < info.range*info.range) currentEnemy = null; } atkCooldown -= dt; base.Update(dt); }
public static TargetCommand WithTarget(ITargetable target) { return new TargetCommand() { Target = target, TimeStamp = RTUtil.GameTime, }; }
public AttackAI(Entity attacker, String targetType) : base() { mAttacker = attacker; mTargetType = targetType; mTarget = null; }
//////////////////////// // EXTERNAL INTERFACE // //////////////////////// public void Set(ITargetable t) { target = t; if (vessel != null && vessel.isActiveVessel) { if (FlightGlobals.fetch != null) FlightGlobals.fetch.SetVesselTarget(target); } }
public virtual void Attack(ITargetable target) { if (CanAttack(target)) { atkCooldown = 1.0f / info.attackSpeed; map.Attacks.Add(new Attack(map, DamageType.Physical, info.attack, info.armorPen, position, this, target, 50)); //target.TakePhysDmg(info.attack, info.armorPen); } }
protected virtual void Update() { if (Input.touchCount == 1) { if (Input.GetTouch(0).phase == TouchPhase.Began) Target = DetectAtTouch(); else if (DetectAtTouch() == null || DetectAtTouch() != Target || Input.GetTouch(0).phase == TouchPhase.Ended) Target = null; } }
private void Initialize() { _cursorPosition = null; _selectableTargets = new List <Point>(); _currentTargetIndex = 0; _area = 0; _targetable = null; _selectionType = SelectionType.None; }
/// <summary> /// True if the craft is sitting on a surface (solid or liquid) rather than on an orbit. /// </summary> public static bool Landed(ITargetable t) { Vessel vessel = t.GetVessel(); return(vessel != null && (vessel.situation == Vessel.Situations.PRELAUNCH || vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.SPLASHED)); }
public Attack(Target target, int range, bool allowMovement) { Target = target; if (target.IsActor) targetable = target.Actor.TraitOrDefault<ITargetable>(); Range = range; AllowMovement = allowMovement; }
public static bool TargetValid() { if (FlightGlobals.ActiveVessel == null || FlightGlobals.ActiveVessel.targetObject == null || FlightGlobals.ActiveVessel.targetObject.GetOrbit() == null || FlightGlobals.ActiveVessel.targetObject.GetOrbit().referenceBody == null || FlightGlobals.ActiveVessel.orbit == null || FlightGlobals.ActiveVessel.orbit.referenceBody == null) { _targetBody = null; _vesselIntersect = false; _bodyIntersect = false; _updated = false; _activeVessel = null; _activeBody = null; _targetObject = null; _targetTransform = null; return(false); } _activeVessel = FlightGlobals.ActiveVessel; _activeBody = FlightGlobals.currentMainBody; _targetObject = _activeVessel.targetObject; if (_targetObject.GetVessel() == null) { if (_targetObject.GetOrbit() == null) { _targetBody = null; _isCelestial = false; _isVessel = false; } else if (_targetObject.GetOrbitDriver().celestialBody != null) { _targetBody = _targetObject.GetOrbitDriver().celestialBody; _isCelestial = true; _isVessel = false; } else { _targetBody = null; _isCelestial = false; _isVessel = false; } } else { _targetBody = null; _isCelestial = false; _isVessel = true; _targetTransform = FlightGlobals.fetch.vesselTargetTransform; _vesselTargetDelta = FlightGlobals.fetch.vesselTargetDelta; } return(true); }
public override void OnTileLeftClicked() { ITargetable target = _inputManager.HoverTile; _ability.Execute(Character); if (_ability.IsTargetValid(target)) { _ability.OnTargetSelected(); } }
/// <summary> /// This method will return a float representing the bearing to a target vector from the actor of the Ai /// </summary> /// <param name="target">The target vector</param> /// <param name="aiActor">The Ai actor</param> /// <returns>A float representing the bearing to the target in radians</returns> protected float GetAngleToTarget(Vector2 target, ITargetable aiActor) { //Get the distance to the target Vector2 distanceToTarget = GetDistance(target, aiActor); //Calculate the angle to the Target double targetAngle = Math.Atan2(distanceToTarget.Y, distanceToTarget.X); return MathHelper.ToDegrees((float)targetAngle); }
public StaticProjectile(AnimatedSprite sprite, ITargetable target, Game gameRef) : base() { projectileSprite = (AnimatedSprite)sprite.Clone(); projectileSprite.CurrentAnimation = AnimationKey.Left; Target = target; projectileSprite.PerformAnimation = true; BoundRect = new BoundRectangle(0, 0, sprite.Width, sprite.Height); Position = Target.BoundRect.BottomCenter - new Vector2(projectileSprite.Width / 2, projectileSprite.Height / 2); }
/// <summary> /// Iterates through _targetingObjects and adds target to each ICanTarget.PotentialTargets, if appropriate. /// Useful when adding a new item to a running state (e.g. ship warps in) /// </summary> /// <param name="target"></param> private void SetForNewTargetable(ITargetable target) { foreach (var pt in _targetingObjects) { if (!pt.Value.OnSameTeam(target) && !pt.Value.PotentialTargets.ContainsKey(target.Id)) { pt.Value.PotentialTargets.Add(target.Id, _targetableObjects[target.Id]); } } }
//Call Event //Single target gets converted to list public void Cast(ITargetable caster, ITargetable enemy) { OnCast(this, caster, new List <ITargetable> { enemy }); if (TimedSpellEffect != null) { enemy.TimedEffects.Add(TimedSpellEffect); } }
public CombatObject(ITargetable workingObject, PointXd position, PointXd vector, long ID, string IDprefix) : base(position, vector, ID, IDprefix) { WorkingObject = workingObject; this.waypointTarget = new CombatWaypoint(); weaponTarget = new List <CombatObject>(1); //eventualy this should be something with the multiplex tracking component. this.cmbt_thrust = new PointXd(0, 0, 0); this.cmbt_accel = new PointXd(0, 0, 0); this.maxRotate = new Compass(0); }
public override ITargetable[] GetTargets(IEffectable source, IGame gameData) { //get the player var player = gameData.TurnLogic.GetPlayer(PlayerSeat); //add it as a target var targets = new ITargetable[] { player }; return(targets); }
public override void Activate(ITargetable target) { MonoBehaviour objectToBoost = target as MonoBehaviour; if (objectToBoost != null) { _damageModifier = Mathf.Clamp(_damageModifier, 0.0f, 1.0f); objectToBoost?.GetComponent <IBoostable>().BoostDefense(_damageModifier); } }
// public Hero target; // TODO // remove public virtual bool Play(ITargetable target = null) { if (!Card.OwnerCanPlay()) { return(false); } target.Damage(damage); Card.owner.hero.TappedMana += Card.manaCost; return(true); }
// public methods public override void Play(ITargetable target) { Debug.Log("PLAY Ability Card: " + Name); base.Play(target); if (PlayEffect != null) { PlayEffect.Activate(target); } }
protected override void ExecuteAction(ITargetable target) { base.ExecuteAction(target); if (target == null) { return; } target.RecieveDamage(attackData.attackStrength); }
/// <summary> /// Re-initialize a model object for the given origin objects. /// </summary> /// <param name="org">Body or vessel to start at</param> public void Reset(ITargetable org) { origin = org; transfers = new List <TransferModel>(); if (!ErrorCondition) { CreateTransfers(org); } }
public override void Activate(ITargetable target) { // test for damageable interace, then apply damage IDamageable objectToDamage = target as IDamageable; // method to retrieve interface without GetComponent if (objectToDamage != null) { objectToDamage.TakeDamage(_damageAmount); } }
private void OnTriggerExit(Collider other) { if (other.gameObject.tag == "HUMAN") { StopAllCoroutines(); InRange = false; ITargetable targetable = other.GetComponent <ITargetable>(); targetable?.UnLock(); } }
/// <summary> /// Construct a model object for the given origin objects. /// </summary> /// <param name="org">Body or vessel to start at</param> public AstrogationModel(ITargetable org) { origin = org; transfers = new List <TransferModel>(); if (!ErrorCondition) { CreateTransfers(org); } }
string CalcTargetDistance(ITargetable obj) { // from Docking Port Alignment Indicator Transform selfTransform = FlightGlobals.ActiveVessel.ReferenceTransform; Transform targetTransform = obj.GetTransform(); Vector3 targetToOwnship = selfTransform.position - targetTransform.position; float distance = targetToOwnship.magnitude; return(Formatter.Distance_short(distance) + " "); }
void LateUpdate() { if (this.navBall == null) { this.navBall = FindObjectOfType <NavBall>(); } if (FlightGlobals.fetch != null && FlightGlobals.ready && FlightGlobals.fetch.activeVessel != null && FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetTargetingMode() == VesselTargetModes.DirectionVelocityAndOrientation) { /// Targeted a Port if I am not mistaken o__o if (this.indicator == null) { SetupIndicator(); } #region "legacy" Code ITargetable targetPort = FlightGlobals.fetch.VesselTarget; Transform targetTransform = targetPort.GetTransform(); Transform selfTransform = FlightGlobals.ActiveVessel.ReferenceTransform; // Position Vector3 targetPortOutVector = targetTransform.forward.normalized; Vector3 rotatedTargetPortInVector = navBall.attitudeGymbal * -targetPortOutVector; this.indicator.transform.localPosition = rotatedTargetPortInVector * navBall.progradeVector.localPosition.magnitude; // Rotation Vector3 v1 = Vector3.Cross(selfTransform.up, -targetTransform.up); Vector3 v2 = Vector3.Cross(selfTransform.up, selfTransform.forward); float ang = Vector3.Angle(v1, v2); if (Vector3.Dot(selfTransform.up, Vector3.Cross(v1, v2)) < 0) { ang = -ang; } this.indicator.transform.rotation = Quaternion.Euler(90 + ang, 90, 270); #endregion // Set opacity float value = Vector3.Dot(indicator.transform.localPosition.normalized, Vector3.forward); value = Mathf.Clamp01(value); this.indicator.GetComponent <MeshRenderer>().materials[0].SetFloat("_Opacity", value); this.indicator.SetActive(indicator.transform.localPosition.z > 0.0d); return; } if (this.indicator != null) { this.indicator.SetActive(false); } }
public void UpdateCoordinates(CelestialBody body) { if (target == null) { return; } Name = target.GetName(); switch (TargetInfo.targetType) { case ProtoTargetInfo.Type.Vessel: var v = target as Vessel; if (v == null) { break; } set_coordinates(v); return; case ProtoTargetInfo.Type.PartModule: var m = target as PartModule; if (m == null || m.vessel == null) { break; } set_coordinates(m.vessel); return; case ProtoTargetInfo.Type.Part: // There may be ITargetable Part derivatives in some mods // ReSharper disable once SuspiciousTypeConversion.Global var p = target as Part; if (p == null || p.vessel == null) { // ProtoTargetInfo.FindTarget() may return a Vessel when the Type == Part goto case ProtoTargetInfo.Type.Vessel; } set_coordinates(p.vessel); return; case ProtoTargetInfo.Type.Generic: var t = target.GetTransform(); if (t == null) { break; } var position = t.position; set_coordinates(body.GetLatitude(position), body.GetLongitude(position), body.GetAltitude(position)); return; } TargetInfo.targetType = ProtoTargetInfo.Type.Null; target = null; Valid = false; }
private List <ITargetable> GetPrioritizedTargets(List <ITargetable> filteredPosibleTargets, Vector2 position) { bool haveAgent = false; ITargetable closestPosibleTarget = null;//estructuras? float closestStructureSqrDist = float.MaxValue; AIAgent closestAgent = null; float closestAgentSqrDist = float.MaxValue; foreach (ITargetable targetable in filteredPosibleTargets) { Vector2 targetPos = targetable.GameObject.transform.position; if (targetable is AIAgent) { haveAgent = true; float sqrDist = Vector2Utilities.SqrDistance(targetPos, position); if (sqrDist < closestAgentSqrDist) { closestAgent = (AIAgent)targetable; closestAgentSqrDist = sqrDist; } } else { if (haveAgent) { continue; } float sqrDist = Vector2Utilities.SqrDistance(targetPos, position); if (sqrDist < closestStructureSqrDist) { closestPosibleTarget = targetable; closestStructureSqrDist = sqrDist; } } } List <ITargetable> returnTargets = new List <ITargetable>(); if (haveAgent) { returnTargets = closestAgent.parent.children.ConvertAll(x => (ITargetable)x); return(returnTargets); } else if (closestPosibleTarget != null) { returnTargets.Add(closestPosibleTarget); return(returnTargets); } else { return(null); } }
public Attack(Target target, int range, bool allowMovement) { Target = target; if (target.IsActor) { targetable = target.Actor.TraitOrDefault <ITargetable>(); } Range = range; AllowMovement = allowMovement; }
public void RemovePanelButton(ITargetable targetToRemove) { ScannerPanelButton button; if (targetButtonPairs.TryGetValue(targetToRemove, out button)) { Destroy(button.gameObject); targetButtonPairs.Remove(targetToRemove); targetToRemove.BecameUntargetable -= HandleTargetBecameUntargetable; } }
private void Start() { Collision = new CollisionCircle(Trans, Mover, Owner, this); CollisionManager.Instance.AddCollidable(Collision); IsAttacking = false; Collision.IsDead = false; Collision.CollidedBaseCircle = null; Target = null; HasTarget = false; isStarted = true; }
/// <summary> /// Check whether a destination is already in the table. /// Intended to avoid unnecessary UI resets. /// </summary> /// <param name="target">Destination to look for</param> /// <returns> /// True if in table, false otherwise. /// </returns> public bool HasDestination(ITargetable target) { for (int i = 0; i < transfers.Count; ++i) { if (transfers[i].destination == target) { return(true); } } return(false); }
public Attack(Map map, DamageType type, float damage, float pen, Vector3 position, ITargetable attacker, ITargetable target, float speed) { this.attacker = attacker; this.map = map; this.type = type; this.position = position; this.target = target; this.damage = damage; this.pen = pen; this.Speed = speed; }
public string findNameForOrbit(Orbit orbit, ITargetable start) { if (start.GetOrbit() == orbit || start.GetOrbit() == null) { return(start.GetName()); } else { return(findNameForOrbit(orbit, start.GetOrbit().referenceBody)); } }
protected virtual bool AcquireTarget() { targetsCount = Physics2D.OverlapCollider(_collider, filter, _targetsBuffer); if (targetsCount > 0) { Target = DefineTarget(); return(true); } Target = null; return(false); }
public void RemoveTargetable(ITargetable target, bool isEnemy = false) { targetsList.Remove(target); if (isEnemy == true) targetsListEnemy.Remove(target); for (int i = targetableListeners.Count - 1; i >= 0; i--) { targetableListeners[i].OnListRemove(target); } }
//////////////////////// // EXTERNAL INTERFACE // //////////////////////// public void Set(ITargetable t) { target = t; if (vessel != null && vessel.isActiveVessel) { if (FlightGlobals.fetch != null) { FlightGlobals.fetch.SetVesselTarget(target); } } }
/// <summary> /// Sub constructor /// </summary> /// <param name="source">The initial location of the sub</param> /// <param name="destination">The destination of the sub</param> /// <param name="launchTime">The time of launch</param> /// <param name="drillerCount">The amount of drillers to launch</param> /// <param name="owner">The owner</param> public Sub(ILaunchable source, ITargetable destination, GameTick launchTime, int drillerCount, Player owner) : base() { this._id = IdGenerator.GetNextId(); this._source = source; this._destination = destination; this._launchTime = launchTime; this._drillerCount = drillerCount; this.Position = source.GetCurrentPosition(); this._owner = owner; this._specialistManager = new SpecialistManager(3); }
public void AttackUpdate(float dt) { targetPos = currentEnemy.GetPosition(); Vector3 diff = currentEnemy.GetPosition() - champion.GetPosition(); float length = diff.Length(); diff /= length; if (champion.InRange(currentEnemy)) { champion.Attack(currentEnemy); targetPos = champion.GetPosition(); } if (currentEnemy.IsDead()) { currentEnemy = null; state = TestControllerState.Laning; } }
private void attackTarget() { Rectangle biggerRect = new Rectangle(mAttacker.CollisionBox.X - mAttacker.CollisionBox.Width / 2, mAttacker.CollisionBox.Y - mAttacker.CollisionBox.Height / 2, mAttacker.CollisionBox.Width * 2, mAttacker.CollisionBox.Height * 2); //if (mAttacker.CollisionBox.Intersects(mTarget.GetCollisionRect())) if (biggerRect.Intersects(mTarget.GetCollisionRect())) { // attack if (mTarget is IDamageable) { ((IDamageable)mTarget).TakeDamage(1, "fire", mAttacker); } CurrentState = State.Done; mTarget = null; } else { Vector2 dir = mTarget.GetPosition() - mAttacker.Position; dir.Normalize(); mAttacker.Velocity = dir * 3.0f; } }
public bool CanAttack(ITargetable target) { Vector3 diff = target.GetPosition() - GetPosition(); return atkCooldown < 0 && diff.LengthSquared() < info.range*info.range; }
private void UpdateKeyboardInput() { UIKeyboard keyboard = manager.UI.Keyboard; // Key Presses Keys[] pressedKeys = keyboard.State.GetPressedKeys(); for (int i = 0; i < pressedKeys.Length; i++) { switch (pressedKeys[i]) { case Keys.W: manager.UI.Camera.MoveForward(); break; case Keys.A: manager.UI.Camera.MoveLeft(); break; case Keys.S: manager.UI.Camera.MoveBack(); break; case Keys.D: manager.UI.Camera.MoveRight(); break; case Keys.Q: manager.UI.Camera.RotateLeft(); break; case Keys.E: manager.UI.Camera.RotateRight(); break; case Keys.R: manager.UI.Camera.RotateDown(); break; case Keys.F: manager.UI.Camera.RotateUp(); break; case Keys.Up: manager.UI.Camera.MoveUp(); break; case Keys.Down: manager.UI.Camera.MoveDown(); break; } } // Key Pushes if (manager.UI.Keyboard.KeyPushed(Keys.Escape)) { if (selected == null) manager.ChangeScreen(new MenuScreen(manager)); else { selected.Updated -= UpdateSelectionInfo; selected = null; SelectionInfoChanged(null, EventArgs.Empty); } } if (manager.UI.Keyboard.KeyPushed(Keys.B)) SetMode(mode == Mode.Build ? Mode.Normal : Mode.Build); if (manager.UI.Keyboard.KeyPushed(Keys.X)) Sim.Settings.Graphics.Default.ShowBBs = !Sim.Settings.Graphics.Default.ShowBBs; if (manager.UI.Keyboard.KeyPushed(Keys.P)) world.Paused = !world.Paused; }
private void Select() { Ray r = GMath.GetRayFromScreenPoint(manager.UI.Mouse.ScreenPositionV, manager.UI.GraphicsDevice.Viewport, manager.UI.Camera.Projection, manager.UI.Camera.View); r.Direction.Normalize(); ITargetable selected = manager.UI.Sim.World.Wildlife.Select(r); if (selected != null) { if (this.selected != null) this.selected.Updated -= UpdateSelectionInfo; this.selected = selected; this.selected.Updated += UpdateSelectionInfo; manager.UI.Camera.SetTrackingTarget(this.selected); SelectionInfoChanged(selected, EventArgs.Empty); } else { //this.selected = null; //SelectedChanged(null, EventArgs.Empty); } }
private void WindowLayout_AddPane_TargetDistance() { intAddDistanceHeight = 272; GUILayout.BeginVertical(); GUILayout.Label(strAlarmEventName + " Details...", KACResources.styleAddSectionHeading); //What are the possible targets?? List<ITargetable> iTargets = new List<ITargetable>(); if (!(KACWorkerGameState.CurrentVesselTarget == null)) { iTargets.Add(KACWorkerGameState.CurrentVesselTarget); //VesselTarget } iTargets.Add(KACWorkerGameState.CurrentVessel.mainBody); //Body we are orbiting if (KACWorkerGameState.SOIPointExists) { iTargets.Add(KACWorkerGameState.CurrentVessel.orbit.nextPatch.referenceBody); //Body we will orbit next } if (intSelectediTarget > iTargets.Count - 1) intSelectediTarget = 0; intAddDistanceHeight += (iTargets.Count*30); //Now give the user the choice GUILayout.BeginHorizontal(); GUILayout.Label("Select Target:",KACResources.styleAddXferName); if (DrawRadioListVertical(ref intSelectediTarget, iTargets.Select(x => x.GetName()).ToArray())) { DebugLogFormatted("Distance Target is:{0}", iTargets[intSelectediTarget].GetName()); } GUILayout.EndHorizontal(); //Set the tgt Object tgtSelectedDistance=iTargets[intSelectediTarget]; string strDistanceName = "Distance"; if (tgtSelectedDistance is CelestialBody) strDistanceName = "Altitude"; //Ask for the target distance/altitude GUILayout.BeginHorizontal(); GUILayout.Label(string.Format("Target {0} (m):",strDistanceName), KACResources.styleAddXferName); dblTargetDistance= Convert.ToInt32(GUILayout.TextField(dblTargetDistance.ToString(),KACResources.styleAddField)); GUILayout.EndHorizontal(); //If the body has an atmosphere then add an option to set the Altitude straight to that if (tgtSelectedDistance is CelestialBody) { if ((tgtSelectedDistance as CelestialBody).atmosphere) { GUILayout.BeginHorizontal(); GUILayout.Label(string.Format("Atmosphere: {0}", (tgtSelectedDistance as CelestialBody).maxAtmosphereAltitude)); if (GUILayout.Button("Set to Edge")) { dblTargetDistance = (tgtSelectedDistance as CelestialBody).maxAtmosphereAltitude; } GUILayout.EndHorizontal(); intAddDistanceHeight += 26; } } //For a vessel give some options for orbits to look forwards GUILayout.BeginVertical(KACResources.styleAddFieldAreas); if (!(tgtSelectedDistance is CelestialBody)) { GUILayout.BeginHorizontal(); GUILayout.Label("Orbits to Search:", KACResources.styleAddHeading, GUILayout.Width(110)); GUILayout.Label(((int)Math.Round((Decimal)fltOrbits_Distance, 0)).ToString(), KACResources.styleAddXferName, GUILayout.Width(25)); fltOrbits_Distance = GUILayout.HorizontalSlider(fltOrbits_Distance, 1, 20); fltOrbits_Distance = (float)Math.Floor((Decimal)fltOrbits_Distance); GUILayout.EndHorizontal(); intAddDistanceHeight += 18; } //What VesselOrbit do we care about Orbit VesselOrbitToCompare=KACWorkerGameState.CurrentVessel.GetOrbit(); if ((KACWorkerGameState.SOIPointExists) && ((tgtSelectedDistance as CelestialBody) == KACWorkerGameState.CurrentVessel.orbit.nextPatch.referenceBody)) { VesselOrbitToCompare = KACWorkerGameState.CurrentVessel.orbit.nextPatch; } //Get the startUT of the orbit Double VesselOrbitStartUT = KACWorkerGameState.CurrentVessel.GetOrbit().StartUT; //Set up some variables intOrbits_Distance = (int)fltOrbits_Distance; int intDistanceOrbitPass = 0; double dblClosestDistance = Double.MaxValue; double dblDistanceUT = 0; double dblOrbitTestDistance = Double.MaxValue; double dblOrbitTestDistanceUT = 0; //If its an Altitude alarm then do this if (tgtSelectedDistance is CelestialBody) { dblOrbitTestDistanceUT = KACUtils.timeOfTargetAltitude(VesselOrbitToCompare, VesselOrbitStartUT, out dblOrbitTestDistance, dblTargetDistance ); dblClosestDistance = dblOrbitTestDistance; dblDistanceUT = dblOrbitTestDistanceUT; } else { //Else Iterate through the orbits to find the target separation for (int intOrbitToTest = 1; intOrbitToTest <= intOrbits_Distance; intOrbitToTest++) { dblOrbitTestDistanceUT = KACUtils.timeOfTargetDistance(VesselOrbitToCompare, tgtSelectedDistance.GetOrbit(), KACWorkerGameState.CurrentTime.UT, intOrbitToTest, out dblOrbitTestDistance, dblTargetDistance ); if (dblOrbitTestDistance < dblClosestDistance) { dblClosestDistance = dblOrbitTestDistance; dblDistanceUT = dblOrbitTestDistanceUT; intDistanceOrbitPass = intOrbitToTest; } } } //Now display what we got GUILayout.BeginHorizontal(); GUILayout.Label(String.Format("{0}:",strDistanceName), KACResources.styleAddHeading, GUILayout.Width(70)); String strDistance = string.Format("{0:#}m", dblClosestDistance); if (dblClosestDistance > 999) strDistance = string.Format("{0:#.0}km", dblClosestDistance / 1000); GUILayout.Label(strDistance, KACResources.styleAddXferName, GUILayout.Width(90)); if (!(tgtSelectedDistance is CelestialBody)) { GUILayout.Label("On Orbit:", KACResources.styleAddHeading); GUILayout.Label(intDistanceOrbitPass.ToString(), KACResources.styleAddXferName); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); //Now do the stuff to draw the alarm button String strMarginConversion = ""; KACTime eventTime = new KACTime(dblDistanceUT); KACTime eventInterval = new KACTime(dblDistanceUT - KACWorkerGameState.CurrentTime.UT); KACTime eventAlarm; KACTime eventAlarmInterval; try { eventAlarm = new KACTime(eventTime.UT - timeMargin.UT); eventAlarmInterval = new KACTime(eventTime.UT - KACWorkerGameState.CurrentTime.UT - timeMargin.UT); } catch (Exception) { eventAlarm = null; eventAlarmInterval = null; strMarginConversion = "Unable to Add the Margin Minutes"; } if ((eventTime.UT > KACWorkerGameState.CurrentTime.UT) && strMarginConversion == "") { if (DrawAddAlarm(eventTime, eventInterval, eventAlarmInterval)) { KACAlarm newAlarm = new KACAlarm(KACWorkerGameState.CurrentVessel.id.ToString(), strAlarmName, strAlarmNotes, eventAlarm.UT, timeMargin.UT, AddType, (AddAction == KACAlarm.AlarmAction.KillWarp), (AddAction == KACAlarm.AlarmAction.PauseGame)); newAlarm.TargetObject = KACWorkerGameState.CurrentVesselTarget; newAlarm.ManNodes = KACWorkerGameState.CurrentVessel.patchedConicSolver.maneuverNodes; Settings.Alarms.Add(newAlarm); Settings.Save(); _ShowAddPane = false; } } else { strMarginConversion = "No Target Distance Approach found"; } if (strMarginConversion != "") GUILayout.Label(strMarginConversion, GUILayout.ExpandWidth(true)); GUILayout.EndVertical(); }
public static void SetLastFlightStatesToCurrent() { VS_TC_GameState.LastSaveGameName = VS_TC_GameState.CurrentSaveGameName; //KACWorkerGameState.LastTime = KACWorkerGameState.CurrentTime;****************************************************************************************************************************** VS_TC_GameState.LastVessel = VS_TC_GameState.CurrentVessel; VS_TC_GameState.LastSOIBody = VS_TC_GameState.CurrentSOIBody; VS_TC_GameState.LastVesselTarget = VS_TC_GameState.CurrentVesselTarget; }
private void getTarget() { int currDistance = 0; int bestDistance = 1000000; // find closest target foreach (Entity ent in UpdateKeeper.getInstance().getEntities()) { if (ent.GetTargetType().Equals(mTargetType) && ent != mAttacker) { currDistance = (int)(Math.Abs(ent.Position.X - mAttacker.Position.X) + Math.Abs(ent.Position.Y - mAttacker.Position.Y)); if (currDistance < bestDistance) { bestDistance = currDistance; mTarget = ent; } } } // if still haven't found if (mTarget == null) { currDistance = 0; bestDistance = 1000000; foreach (LevelElement ele in UpdateKeeper.getInstance().getLevelElements()) { if (ele.GetTargetType().Equals(mTargetType)) { currDistance = (int)(Math.Abs(ele.Position.X - mAttacker.Position.X) + Math.Abs(ele.Position.Y - mAttacker.Position.Y)); if (currDistance < bestDistance) { bestDistance = currDistance; mTarget = ele; } } } } }
public void RemoveFromPartitioning(ITargetable target) { Vector3 position = target.GetPosition(); int x = (int)(position.X / PartitioningDensity); int y = (int)(position.Z / PartitioningDensity); TargetPartitioning[x, y].Remove(target); }
public StandardAI(ITargetable inTarget) { this.target = inTarget; moveAI = new MoveToTargetAI(target); fleeAI = new FleeTargetAI(target); }
/// <summary> /// Draws the target selector structure. /// </summary> public override void Draw(SectionModule section) { if (FlightGlobals.fetch.VesselTarget == null) { if (this.vesselType == VesselType.Unknown && !this.typeIsBody) { this.DrawSearch(); if (this.searchQuery.Length == 0) { this.DrawTypes(); } else { this.DrawTargetList(); } } else { this.DrawBackToTypes(); this.DrawTargetList(); } } else { this.DrawTarget(section); } if (this.targetObject != FlightGlobals.fetch.VesselTarget) { this.targetObject = FlightGlobals.fetch.VesselTarget; this.ResizeRequested = true; } }
private void SetTargetAs(ITargetable target) { FlightGlobals.fetch.SetVesselTarget(target); this.targetObject = target; this.ResizeRequested = true; }
void InitDocking() { lastTarget = core.target.Target; try { vesselBoundingBox = vessel.GetBoundingBox(); targetBoundingBox = lastTarget.GetVessel().GetBoundingBox(); if (!overrideTargetSize) targetSize = targetBoundingBox.size.magnitude; else targetSize = (float)overridenTargetSize.val; if (!overrideSafeDistance) safeDistance = vesselBoundingBox.size.magnitude + targetSize + 0.5f; else safeDistance = (float)overridenSafeDistance.val; if (core.target.Target is ModuleDockingNode) acquireRange = ((ModuleDockingNode)core.target.Target).acquireRange * 0.5; else acquireRange = 0.25; } catch (Exception e) { print(e); } if (zSep < 0) //we're behind the target dockingStep = DockingStep.WRONG_SIDE_BACKING_UP; else if (lateralSep.magnitude > dockingcorridorRadius) // in front but far from docking axis if (zSep < targetSize) dockingStep = DockingStep.BACKING_UP; else dockingStep = DockingStep.MOVING_TO_START; else dockingStep = DockingStep.DOCKING; }
void InitDocking() { lastTarget = core.target.Target; try { Vector3Pair vesselBoundingBox = vessel.GetBoundingBox(); Vector3Pair targetBoundingBox = lastTarget.GetVessel().GetBoundingBox(); targetSize = Mathf.Max(targetBoundingBox.p1.magnitude, targetBoundingBox.p2.magnitude); safeDistance = Mathf.Max(vesselBoundingBox.p1.magnitude, vesselBoundingBox.p2.magnitude) + targetSize; if (core.target.Target is ModuleDockingNode) acquireRange = ((ModuleDockingNode)core.target.Target).acquireRange * 0.5; else acquireRange = 0.25; } catch (Exception e) { print(e); } if (zSep < 0) //we're behind the target dockingStep = DockingStep.WRONG_SIDE_BACKING_UP; else if (lateralSep.magnitude > dockingcorridorRadius) // in front but far from docking axis if (zSep < targetSize) dockingStep = DockingStep.BACKING_UP; else dockingStep = DockingStep.MOVING_TO_START; else dockingStep = DockingStep.DOCKING; }
public static void SetTarget(ITargetable val) { FlightGlobals.fetch.SetVesselTarget(val); }
public static void SetTarget(ITargetable val) { //if (val is Vessel) //{ FlightGlobals.fetch.SetVesselTarget(val); //} //else if (val is CelestialBody) //{/ // } }
public void AddToPartitioning(ITargetable target) { Vector3 position = target.GetPosition(); int x = (int)(position.X / PartitioningDensity); int y = (int)(position.Z / PartitioningDensity); TargetPartitioning[x, y].Add(target); }
public override void Update(float dt) { List<ITargetable> targets = map.GetTargetsInRange(GetPosition(), info.viewRadius); for (int x = 0; x < targets.Count; x++) { if (targets[x] == this) continue; if (currentEnemy == null && targets[x].GetTeam() != GetTeam() && targets[x].IsTargetable(GetTeam())) { currentEnemy = targets[x]; } Vector3 diff = targets[x].GetPosition() - GetPosition(); float length = diff.Length(); diff /= length; if (length < 10 && length != 0) Move(-diff * dt); } if (currentEnemy == null) { targetPos = nextTarget; Vector3 diff = nextTarget - GetPosition(); float length = diff.Length(); diff /= length; if (length < 5) { targetID++; if (targetID >= lane.Waypoints.Length) targetID = lane.Waypoints.Length - 1; nextTarget = lane.Waypoints[targetID]; } } else { targetPos = currentEnemy.GetPosition(); Vector3 diff = currentEnemy.GetPosition() - GetPosition(); float length = diff.Length(); diff /= length; if (length < info.range) { Attack(currentEnemy); targetPos = GetPosition(); } else { ITargetable test = GetClosestEnemy(); if (test != null) currentEnemy = test; } if (currentEnemy.IsDead() || length > info.viewRadius) currentEnemy = null; } Vector3 tp; if (evade) tp = evasionTarget; else tp = targetPos; Vector3 tdiff = tp - GetPosition(); float tlength = tdiff.Length(); tdiff /= tlength; if (tlength > 0) { Vector3 predictedPosition = GetPosition() + tdiff * info.movespeed * 0.5f; if (map.InCollision(predictedPosition)) { evade = true; ICollidable collider = map.GetCollider(predictedPosition); if (collider != null) { Vector3 vertex = collider.Bounds.GetEdgeToCircumvent(GetPosition(), tp); Vector3 dir = vertex-collider.Bounds.Center; dir/=dir.Length(); evasionTarget = vertex + dir*Size; } } Move(tdiff * info.movespeed * dt); } if (evade && tlength < 1) evade = false; base.Update(dt); }
public override void OnFixedUpdate() { //Restore the saved target when we are made active vessel if (!wasActiveVessel && vessel.isActiveVessel) { if (target != null && target.GetVessel() != null) { FlightGlobals.fetch.SetVesselTarget(target); } } //notice when the user switches targets if (vessel.isActiveVessel && target != FlightGlobals.fetch.VesselTarget) { target = FlightGlobals.fetch.VesselTarget; if (target is Vessel && ((Vessel)target).LandedOrSplashed && (((Vessel)target).mainBody == vessel.mainBody)) { targetBody = vessel.mainBody; targetLatitude = vessel.mainBody.GetLatitude(target.GetTransform().position); targetLongitude = vessel.mainBody.GetLongitude(target.GetTransform().position); } } // .23 temp fix until I understand better what's going on if (targetBody == null) targetBody = vessel.mainBody; //Update targets that need updating: if (target is DirectionTarget) ((DirectionTarget)target).Update(targetDirection); else if (target is PositionTarget) ((PositionTarget)target).Update(targetBody, targetLatitude, targetLongitude); wasActiveVessel = vessel.isActiveVessel; }