예제 #1
0
            private bool RemoveReachedObjective()
            {
                this.Objective = null;
                List <MyWaypointInfo> route = new List <MyWaypointInfo>();

                remotePilot.GetWaypointInfo(route);
                if (route.Count > 0)
                {
                    MyWaypointInfo nextWaypoint = route.First();
                    route.RemoveAt(0);
                    remotePilot.ClearWaypoints();
                    switch (remotePilot.FlightMode)
                    {
                    case FlightMode.OneWay:
                        break;

                    case FlightMode.Circle:
                        route.Add(nextWaypoint);
                        break;

                    case FlightMode.Patrol:     // behave as one way
                        uIManager.printOnScreens("service", "[AP] Patrol not implemented yet!");
                        break;
                    }
                    foreach (MyWaypointInfo wp in route)
                    {
                        remotePilot.AddWaypoint(wp);
                    }
                    //Need to reset the autopilot status to true after clearing the queue
                    remotePilot.SetAutoPilotEnabled(true);
                }
                return(route.Count > 0);
            }
예제 #2
0
        public bool TurnForward()
        {
            control.ClearWaypoints();
            Vector3 controlWorldPos = Me.CubeGrid.GridIntegerToWorld(control.Position);

            control.AddWaypoint(controlWorldPos + forward * 100, "[AUTO]Forward");
            SwitchFlyMode(false);
            if (!control.IsAutoPilotEnabled)
            {
                control.SetAutoPilotEnabled(true);
            }
            return(Vector3.Dot(Me.CubeGrid.GridIntegerToWorld(control.Position + Base6Directions.GetIntVector(control.Orientation.Forward)) - controlWorldPos, forward) < 0.1f);
        }
예제 #3
0
            public override void DoOnDirectMasterMsg(MyIGCMessage msg)
            {
                p.Echo("Getting msg from master");
                if (msg.Tag == ShipFormationMaster.TAG_FORMATION)
                {
                    GPS center = new GPS(msg.Data.ToString());
                    p.Echo("Getting formation msg from master : ");

                    IMyRemoteControl r = GetRemote();

                    r.ClearWaypoints();

                    int    nbWP     = 18;
                    double angleTmp = 0;
                    double angleDeg = 360 / nbWP;
                    for (int i = 0; i < nbWP; ++i)
                    {
                        GPS            wp   = center.ComputeCoordinate(ShipFormationMaster.DISTANCE, DegreeToRadian(angleTmp));
                        MyWaypointInfo dest = new MyWaypointInfo("WP_" + i, wp.x, wp.y, wp.z);
                        r.AddWaypoint(dest);
                        angleTmp += angleDeg;
                    }

                    GetLight().SetValue("Color", new Color(0, 255, 0));

                    r.FlightMode = FlightMode.Circle;
                    r.SetCollisionAvoidance(false);
                    r.SetAutoPilotEnabled(true);
                }
            }
예제 #4
0
        public IEnumerator <int> Forward() //uses rotationGoal
        {
            _currentState = "Forward()";
            yield return(0);

            _remote.ClearWaypoints();
            _remote.SpeedLimit = 2.0f;
            _remote.FlightMode = FlightMode.OneWay;
            var remotePos = _remote.GetPosition();
            var diff      = remotePos - _remote.CenterOfMass;
            var wp        = 2.5 * (_basis[_rotationGoal]) + remotePos + diff;

            _remote.AddWaypoint(wp, "Forward");
            var curPosition = remotePos;

            yield return(0);

            while (Vector3D.DistanceSquared(curPosition, wp) > 2) // requires tweaking
            {
                _remote.SetAutoPilotEnabled(true);
                curPosition = _remote.GetPosition();
                yield return(0);
            }
            _remote.SetAutoPilotEnabled(false);
            yield return(1);
        }
예제 #5
0
 private void GoTo(Vector3D pos, string label)
 {
     Stop();
     rc.AddWaypoint(new MyWaypointInfo(label, pos));
     rc.FlightMode = FlightMode.OneWay;
     rc.SetAutoPilotEnabled(true);
 }
예제 #6
0
        void LaunchDrone(EncounterType encounterType, IMyRemoteControl remote, IMyEntity entity, Vector3D despawnCoords)
        {
            if (remote != null && encounterType == EncounterType.TransientCargoship)
            {
                remote.ClearWaypoints();
                remote.FlightMode = Sandbox.ModAPI.Ingame.FlightMode.OneWay;
                remote.AddWaypoint(despawnCoords, "DespawnTarget");
                remote.SetAutoPilotEnabled(true);
                remote.SpeedLimit = CARGOSHIP_SPEED;
                Util.Notify("Autopilot set");
            }

            SpawnedShip ship = new SpawnedShip();

            ship.entityId = entity.EntityId;
            if (encounterType == EncounterType.Static || encounterType == EncounterType.TransientEncounter)
            {
                m_empireData.encounters.Add(ship);
            }
            else if (encounterType == EncounterType.TransientCargoship)
            {
                m_empireData.civilianFleet.Add(ship);
            }
            else if (encounterType == EncounterType.TransientAttackship)
            {
                m_empireData.militaryFleet.Add(ship);
            }
            ship.despawnTick = GlobalData.world.currentTick + Tick.Minutes(10);

            if (encounterType == EncounterType.TransientAttackship || encounterType == EncounterType.TransientCargoship)
            {
                BotManager.CreateBot(BotManager.BotType.CargoShip, this, ship, remote);
            }
            Util.Log("Drone Prepped!");
        }
예제 #7
0
 void Target(Vector3 position)
 {
     target = position;
     mainControl.ClearWaypoints();
     mainControl.AddWaypoint(position, "Target Destination");
     mainControl.FlightMode = FlightMode.OneWay;
     mainControl.SetAutoPilotEnabled(true);
 }
 private void setupAndStartDrone(Vector3D Target, string WP_Name, bool dockingMode)
 {
     RemoteControl.SetAutoPilotEnabled(false);
     RemoteControl.ClearWaypoints();
     RemoteControl.AddWaypoint(Target, WP_Name);
     RemoteControl.ApplyAction("CollisionAvoidance_On");
     RemoteControl.ApplyAction("AutoPilot_On");
     RemoteControl.ApplyAction((dockingMode)? "DockingMode_On" : "DockingMode_Off");
     RemoteControl.SetAutoPilotEnabled(true);
 }
예제 #9
0
        void CloneWaypoints()
        {
            if (_patrolEnabled)
            {
                if (_patrolRoute == null)
                {
                    _patrolRoute = new List <MyWaypointInfo>();
                    if (_controllerBlock == null)
                    {
                        _remoteBlock.GetWaypointInfo(_patrolRoute);
                    }
                    else
                    {
                        _controllerBlock.GetWaypointInfo(_patrolRoute);
                    }
                }

                if (_controllerBlock != null)
                {
                    _remoteBlock.ClearWaypoints();
                    foreach (var item in _patrolRoute)
                    {
                        _remoteBlock.AddWaypoint(item);
                    }
                }

                if (_controllerBlock != null)
                {
                    _opMode = OperationMode.RemoteCtrl;
                }
                else
                {
                    _opMode = OperationMode.SingleCtrl;
                }
            }
            else
            {
                _opMode = OperationMode.Stationary;
            }
        }
예제 #10
0
 public void NotReady()
 {
     StartElev = Elev;
     SeaLevel  = MinR;
     RControllers.SetAutoPilotEnabled(false);
     RControllers.FlightMode = FlightMode.OneWay;
     RControllers.Direction  = Base6Directions.Direction.Forward;
     RControllers.SpeedLimit = 200;
     StartLocation           = RController.GetPosition();
     RControllers.ClearWaypoints();
     GyroStartLocation = RGyro.GetPosition();
     RConStartLocation = RCon.GetPosition();
     RefDist           = Math.Round(Vector3D.Distance(GyroStartLocation, StartLocation), 2);               //Distance between RC and Gyro
     Distance          = ((GyroStartLocation - StartLocation) * ((TargetAltitude - StartElev) / RefDist)); //Calculates Distance to Target
     TargetLocation    = (StartLocation + Distance);                                                       ////Calculates Co-ords for Target
     RefDist           = Math.Round(Vector3D.Distance(RConStartLocation, StartLocation), 2);               //Distance between RC and Gyro
     Distance          = ((RConStartLocation - StartLocation) * ((AppTarget + StartElev) / RefDist));      //Calculates Distance to Approach (1000m)
     AppLocation       = (StartLocation + Distance);                                                       ////Calculates Co-ords for Target
     RControllers.AddWaypoint(TargetLocation, (Ship + "Target Location"));
     Init = true;
     Main("Ready");
     return;
 }
예제 #11
0
        public void Main(string argument, UpdateType updateSource)
        {
            // The main entry point of the script, invoked every time
            // one of the programmable block's Run actions are invoked,
            // or the script updates itself. The updateSource argument
            // describes where the update came from. Be aware that the
            // updateSource is a  bitfield  and might contain more than
            // one update type.
            //
            // The method itself is required, but the arguments above
            // can be removed if not needed.

            IMyLaserAntenna  antenna       = (IMyLaserAntenna)GridTerminalSystem.GetBlockWithName("Main Laser Antenna");
            IMyRemoteControl remoteControl = (IMyRemoteControl)GridTerminalSystem.GetBlockWithName("Main Remote Control");

            if (antenna != null && remoteControl != null)
            {
                if (antenna.Status != MyLaserAntennaStatus.Connected)
                {
                    if (antenna.Status != MyLaserAntennaStatus.RotatingToTarget)
                    {
                        if (antenna.Status != MyLaserAntennaStatus.SearchingTargetForAntenna)
                        {
                            if (antenna.Status != MyLaserAntennaStatus.Connecting)
                            {
                                antenna.Connect();
                            }
                        }
                    }

                    remoteControl.ClearWaypoints();
                    remoteControl.AddWaypoint(antenna.TargetCoords, "Antenna Target");
                    remoteControl.SpeedLimit = 10;
                    remoteControl.Direction  = Base6Directions.Direction.Forward;
                    remoteControl.SetAutoPilotEnabled(true);
                    regainedConnection = false;
                }
                else if (!regainedConnection)
                {
                    remoteControl.SetAutoPilotEnabled(false);
                    regainedConnection = true;
                }
            }
        }
예제 #12
0
        public void Main(string args)
        {
            if (args.StartsWith("AntennaPosition"))
            {
                Echo("Recived message");
                Vector3 coords;
                if (StringToVector3(args, out coords))
                {
                    var currentPos = remoteControl.GetPosition();

                    if ((currentPos - coords).Length() < NotDisturbDistance)
                    {
                        remoteControl.SetAutoPilotEnabled(false);
                    }
                    remoteControl.ClearWaypoints();
                    remoteControl.AddWaypoint(coords, "Destination");
                    Echo($"Move to {coords.ToString()}");
                    remoteControl.SetAutoPilotEnabled(true);
                }
            }
        }
        /**
         * AreaDefenceDroneAI
         * ==============================
         * Copyright (c) 2015 Thomas Klose <*****@*****.**>
         * Source:
         *
         * Summary
         * ------------------------------
         *
         *
         * Abstract
         * ------------------------------
         *
         *
         * Example
         * ------------------------------
         *
         */
        void Main(string args)
        {
            IMyRemoteControl RemoteControl = GridTerminalSystem.GetBlockWithName("RC") as IMyRemoteControl;

            if (RemoteControl != null)
            {
                //GPS: ORIGIN: -56148.91:23763.12:-2721.73:
                Vector3D origin = new Vector3D(-56148.91, 23763.12, -2721.73);


                RemoteControl.SetAutoPilotEnabled(false);
                RemoteControl.ClearWaypoints();
                RemoteControl.AddWaypoint(origin, "WP_Name");
                RemoteControl.ApplyAction("CollisionAvoidance_On");
                RemoteControl.ApplyAction("AutoPilot_On");
                RemoteControl.ApplyAction("DockingMode_Off");
                RemoteControl.SetAutoPilotEnabled(true);

                // ADDAI Brain = new ADDAI(RC, GridTerminalSystem, origin, 500.0, 50.0);
                // Brain.run();
            }
        }
예제 #14
0
        internal override void Update()
        {
            CheckEscortsAlive();
            if (!leader.IsControlledByFaction("GCORP"))
            {
                GroupState = NpcGroupState.Disbanding;
                InitiateDisbandProtocols();
            }
            else if ((GroupState == NpcGroupState.Travelling || GroupState == NpcGroupState.InCombat) &&
                     Vector3D.DistanceSquared(Destination, leader.GetPosition()) < 300.0 * 300)    // increase to 300 to allow for variations in height. V26
//                     && Vector3D.DistanceSquared(Destination, leader.GetPosition()) < 200.0*200) // increase to 200 to allow for variations in height.
//                     && Vector3D.Distance(Destination, leader.GetPosition()) < 100.0)
            {
                string sBeacons    = "";
                var    slimBlocks2 = new List <IMySlimBlock>();
                leader.GetBlocks(slimBlocks2, b => b.FatBlock is IMyBeacon);
                foreach (var slim2 in slimBlocks2)
                {
                    var beacon = slim2.FatBlock as IMyBeacon;
                    sBeacons += beacon.CustomName;
                }

                ModLog.Info("Group Arrived at destination: " + leader.CustomName + " " + sBeacons);
                ArrivalObserver.GroupArrivedIntact();
                audioSystem.PlayAudioRandomChance(0.1, AudioClip.ConvoyArrivedSafely);
                GroupState = NpcGroupState.Disbanding;
                InitiateDisbandProtocols();
                ResetBeaconNames();
            }

            // ModLogs are for DEBUG nav script
//            ModLog.Info("Convoy update:" + leader.CustomName+" ID:"+leader.EntityId.ToString() + " State:"+GroupState.ToString());
            if ((GroupState == NpcGroupState.Travelling))
            {
                var currentTime = MyAPIGateway.Session.GameDateTime;
                if (GroupSpawnTime + convoyInitiateTime < currentTime)
                {
                    leader.SetAllBeaconNames(null, 20000f);
                }
                bool bKeenAutopilotActive = false;
                var  slimBlocks           = new List <IMySlimBlock>();
                leader.GetBlocks(slimBlocks, b => b.FatBlock is IMyRemoteControl);
                IMyRemoteControl remoteControl = null;
                foreach (var slim in slimBlocks)
                {
                    remoteControl        = slim.FatBlock as IMyRemoteControl;
                    bKeenAutopilotActive = remoteControl.IsAutoPilotEnabled;
//                    ModLog.Info("Keen Autopilot:" + bKeenAutopilotActive.ToString());
                    break;
                }

                slimBlocks.Clear();
                leader.GetBlocks(slimBlocks, b => b.FatBlock is IMyProgrammableBlock);
                foreach (var slim in slimBlocks)
                {
                    var block = slim.FatBlock as IMyProgrammableBlock;
                    if (block == null)
                    {
                        continue;
                    }

                    if (block.CustomName.Contains("NAV"))
                    {
                        if (!bKeenAutopilotActive &&
                            GroupSpawnTime + convoyInitiateTime < currentTime    // delay check for mode change.
                            )
                        {
                            if (//!bKeenAutopilotActive &&
                                block.DetailedInfo.Contains("mode=0") || block.DetailedInfo.Contains("mode=-1"))
                            {
                                if (remoteControl == null)
                                {
                                    // nothing left to do.  Remove it (and try again)
                                    GroupState = NpcGroupState.Inactive; // this will cause NpcGroupManager to spawn a new convoy to replace this one.
                                    return;
                                }
                                // force it to use Keen Autopilot
                                remoteControl.ClearWaypoints();
                                remoteControl.AddWaypoint(Destination, "Target");
                                remoteControl.SpeedLimit = 10;
                                remoteControl.SetAutoPilotEnabled(true);

                                /*
                                 * // debug output
                                 * var slimBlocks2 = new List<IMySlimBlock>();
                                 * leader.GetBlocks(slimBlocks2, b => b.FatBlock is IMyBeacon);
                                 * string sBeacons = "";
                                 * foreach(var slim2 in slimBlocks2)
                                 * {
                                 *  var beacon = slim2.FatBlock as IMyBeacon;
                                 *  sBeacons += beacon.CustomName;
                                 * }
                                 *
                                 * // it didn't get the command!
                                 * //                                GroupState = NpcGroupState.Inactive; // this will cause NpcGroupManager to spawn a new convoy to replace this one.
                                 * ModLog.Info("Autopilot recovery because leader NAV not in correct mode: "+ sBeacons);
                                 */
                            }
                            break;
                        }
//                        ModLog.Info("PB:"+block.CustomName+"\n"+"DetailedInfo=:\n" + block.DetailedInfo);
                    }
                }

                // Following is just debug info

                /*
                 * leader.GetBlocks(slimBlocks, b => b.FatBlock is IMyGyro);
                 * foreach (var slim in slimBlocks)
                 * {
                 *  var block = slim.FatBlock as IMyGyro;
                 *  if (block!=null && block.CustomName.Contains("NAV"))
                 *  {
                 *      ModLog.Info("G:"+block.CustomName + "\n");
                 *  }
                 * }
                 */
            }

            if (GroupState == NpcGroupState.Disbanding)
            {
                AttemptDespawning();
                return;
            }

            if (DuckUtils.IsAnyPlayerNearPosition(leader.GetPosition(), 1000) && GroupState == NpcGroupState.Travelling)
            {
                GroupState = NpcGroupState.InCombat;
                InitiateAttackProtocols();
            }

            if (GroupState == NpcGroupState.InCombat)
            {
                var player = DuckUtils.GetNearestPlayerToPosition(leader.GetPosition(), 4000);
                if (player == null)
                {
                    GroupState = NpcGroupState.Travelling;       // Return to normal, cowardly players have run off or died
                    ResetBeaconNames();
                    if (escortDic.Count > 0)                     //todo maybe check if the escorts are actually alive? Dunno if doing this already
                    {
                        audioSystem.PlayAudio(AudioClip.DisengagingFromHostile, AudioClip.TargetLost);
                    }
                    else
                    {
                        audioSystem.PlayAudio(AudioClip.PursuitEvaded, AudioClip.SensorsLostTrack);
                    }
                }
                else
                {
                    SendArmedEscortsNearPosition(player.GetPosition());                     // Use same position as when escorting, to avoid collisions
                }
            }

            if (GroupState == NpcGroupState.Travelling)
            {
                foreach (var entry in escortDic)
                {
                    SendEscortToGrid(entry.Key, entry.Value, leader);
                }
            }
        }
예제 #15
0
        public void Main(string argument)
        {
            switch (state)
            {
            case Mode.Idle:
                if (argument == "Wreck")
                {
                    state = Mode.Grinding;
                }
                if (argument == "Start")
                {
                    if (visor.AvailableScanRange >= 1000)
                    {
                        Echo("Search for target");
                        target = visor.Raycast(1000);
                    }
                }
                if (target.IsEmpty())
                {
                    Echo("Target not found");
                    return;
                }
                Echo("Target found!");
                Vector3D targetPos;
                if (target.HitPosition != null)
                {
                    targetPos = (Vector3D)target.HitPosition;
                    Vector3D targetVector = targetPos - control.GetPosition();
                    targetVector.Normalize();
                    targetPos = targetPos - 20 * targetVector;
                    control.ClearWaypoints();
                    control.AddWaypoint(targetPos, "Target");
                    control.GetActionWithName("CollisionAvoidance_On").Apply(control);
                    control.GetActionWithName("DockingMode_On").Apply(control);
                    //!!!Erst einstellungen, dann aktivieren!!!
                    control.GetActionWithName("AutoPilot_On").Apply(control);
                    state = Mode.Flying;
                }
                break;

            case Mode.Flying:
                break;

            case Mode.Grinding:
                List <string> activSensors = CheckSensors(mainGrinderSensors);
                Vector3D      instructions = CheckDirection(activSensors);
                instructions = CheckObstacles(instructions);
                float  massFactor   = control.CalculateShipMass().TotalMass / baseMass;
                double thrustFactor = Math.Pow(2, massFactor);
                foreach (IMyThrust thrust in allThruster)
                {
                    thrust.SetValueFloat("Override", 0);
                }
                SetGyros(0, 0, 0);
                Echo("Vector is: " + (int)instructions.X + " " + (int)instructions.Y + " " + (int)instructions.Z);
                if (activSensors.Count == 0 && CheckSensors(mainCollisionSensors).Count == 0)
                {
                    Echo("Going forward");
                    foreach (IMyThrust thrust in thruster[Side.Front])
                    {
                        thrust.SetValueFloat("Override", (float)(10 * thrustFactor));
                    }
                }
                else if (IsZero(instructions))
                {
                    Echo("Is zero");
                    foreach (IMyThrust thrust in thruster[Side.Back])
                    {
                        thrust.SetValueFloat("Override", (float)(5 * thrustFactor));
                    }
                }
                else
                {
                    Echo("Working");
                    int basethrust = 35;
                    if (instructions.Z == 0)
                    {
                        instructions.X = Math.Sign(instructions.X) * thrustFactor;
                        instructions.Y = Math.Sign(instructions.Y) * thrustFactor;
                        SetGyros((float)instructions.Y, (float)instructions.X, 0);
                        instructions.X = -instructions.X;
                        instructions.Y = -instructions.Y;
                        basethrust     = 5;
                    }
                    List <IMyThrust> neededThruster = instructions.X > 0 ? thruster[Side.Right] : thruster[Side.Left];
                    if (instructions.X != 0)
                    {
                        foreach (IMyThrust thrust in neededThruster)
                        {
                            thrust.SetValueFloat("Override", (float)(thrustFactor * basethrust));
                        }
                        foreach (IMyThrust thrust in thruster[Side.Front])
                        {
                            thrust.SetValueFloat("Override", (float)(5 * thrustFactor));
                        }
                    }
                    if (instructions.Y != 0)
                    {
                        neededThruster = instructions.Y > 0 ? thruster[Side.Up] : thruster[Side.Down];
                        foreach (IMyThrust thrust in neededThruster)
                        {
                            thrust.SetValueFloat("Override", (float)(thrustFactor * basethrust));
                        }
                        foreach (IMyThrust thrust in thruster[Side.Front])
                        {
                            thrust.SetValueFloat("Override", (float)(5 * thrustFactor));
                        }
                    }
                }
                break;
            }
        }
예제 #16
0
        string doInit()
        {
            // initialization of each module goes here:

            // when all initialization is done, set init to true.

            Echo(gtsAllBlocks.Count.ToString() + " Blocks");

            Echo("Init:" + currentInit);
            if (currentInit == 0)
            {
                //        StatusLog("clear", textLongStatus, true); // only MAIN module should clear long status on init.
                StatusLog(DateTime.Now.ToString() + " " + OurName + ":" + moduleName + ":INIT", textLongStatus, true);

                /*
                 * add commands to set modes
                 * if(!modeCommands.ContainsKey("launchprep")) modeCommands.Add("launchprep", MODE_LAUNCHPREP);
                 */
                sInitResults += gridsInit();
                initLogging();
                initTimers();
                sInitResults += SerializeInit();

                Deserialize(); // get info from savefile to avoid blind-rewrite of (our) defaults
            }
            else if (currentInit == 1)
            {
                Deserialize();// get info from savefile to avoid blind-rewrite of (our) defaults

//                sInitResults += BlockInit();
                sInitResults += DefaultOrientationBlockInit();
                initCargoCheck();
                initPower();
                sInitResults += thrustersInit(shipOrientationBlock);
                sInitResults += gyrosetup();
//                if (gtsAllBlocks.Count < 300) currentInit = 2; // go ahead and do next step.
                if (shipOrientationBlock is IMyRemoteControl)
                {
                    Vector3D         playerPosition;
                    bool             bGotPlayer = ((IMyRemoteControl)shipOrientationBlock).GetNearestPlayer(out playerPosition);
                    IMyRemoteControl myR        = (IMyRemoteControl)shipOrientationBlock;
                    myR.SetCollisionAvoidance(false);
                    myR.SetDockingMode(false);
                    myR.Direction  = Base6Directions.Direction.Forward;
                    myR.FlightMode = FlightMode.OneWay;
                    myR.ClearWaypoints();
                    myR.AddWaypoint(playerPosition, "Name");
                }
            }
            if (currentInit == 2)
            {
                sInitResults += wheelsInit(shipOrientationBlock);
                sInitResults += rotorsNavInit();

                sInitResults += connectorsInit();
                sInitResults += tanksInit();
                sInitResults += drillInit();
//                if (gtsAllBlocks.Count < 100) currentInit = 3; // go ahead and do next step.
            }
            if (currentInit == 3)
            {
                sInitResults += camerasensorsInit(shipOrientationBlock);
                sInitResults += ejectorsInit();

                sInitResults += antennaInit();
                sInitResults += gasgenInit();

                autoConfig();
                bWantFast = false;

                if (bGotAntennaName)
                {
                    sBanner = "*" + OurName + ":" + moduleName + " V" + sVersion + " ";
                }

                if (sBanner.Length > 34)
                {
                    sBanner = OurName + ":" + moduleName + "\nV" + sVersion + " ";
                }
                if (shipOrientationBlock is IMyShipController)
                {
                    MyShipMass myMass;
                    myMass = ((IMyShipController)shipOrientationBlock).CalculateShipMass();

                    gridBaseMass = myMass.BaseMass;
                }

                sInitResults += modeOnInit(); // handle mode initializing from load/recompile..

                init = true;                  // we are done
            }

            currentInit++;
            if (init)
            {
                currentInit = 0;
            }

            Log(sInitResults);

            return(sInitResults);
        }
예제 #17
0
            private void HandleFacing(TempData tempData)
            {
                Vector3 desiredRotSpeed;

                if (command == null)
                {
                    desiredRotSpeed = Vector3.Zero;
                }
                else
                {
                    var navigationData = command.GetNavData(program);
                    //Vector3 targetDirection = chosenTarget.Position - Me.CubeGrid.GridIntegerToWorld( Me.Position );
                    //targetDirection.Normalize();
                    Vector3 des = navigationData.desiredForward.Value;
                    //VrageMath doesn't have Vector3 * Matrix3x3 multiplication
                    //navigationData.desiredFacing = new Vector3( Vector3.Dot(des, directionAdjustMatrix.Col0), Vector3.Dot( des, directionAdjustMatrix.Col1 ), Vector3.Dot( des, directionAdjustMatrix.Col2 ) );

                    List <IMyRadioAntenna> antenna = new List <IMyRadioAntenna>();
                    GridTerminalSystem.GetBlocksOfType <IMyRadioAntenna>(antenna);
                    antenna[0].CustomName = "Desired Facing: " + navigationData.desiredForward;

                    desiredRotSpeed = tempData.facing.Cross(navigationData.desiredForward.Value);   //get direction of desired rotation
                    desiredRotSpeed.Normalize();
                    //Echo("Dd: " + desiredSpeed);
                    desiredRotSpeed.Multiply(0.5f - tempData.facing.Dot(navigationData.desiredForward.Value) / 2);     //get magnitude of desired rotation
                                                                                                                       //Echo( "Desired speed: " + desiredSpeed.Length() );
                                                                                                                       //desiredSpeed = desiredDir - rotSpeed;
                                                                                                                       //Echo( string.Format( "Facing: {0} TargetDir:{1}", facing, targetDirection ) );
                }

                Vector3 targetRotation = new Vector3(tempData.facingLeft.Dot(desiredRotSpeed), tempData.facingUp.Dot(desiredRotSpeed), tempData.facing.Dot(desiredRotSpeed));


                //targetRotation = new Vector3( 0,targetRotation.Y,0 );

                //program.Echo( "TR:   " + targetRotation );

                if (useControlBlock)
                {
                    List <IMyRemoteControl> control = new List <IMyRemoteControl>();
                    GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(control);
                    if (shouldSetWaypoint == 0)
                    {
                        if (control.Count > 0)
                        {
                            IMyRemoteControl cntrl = control[0];
                            cntrl.ControlThrusters = false;
                            cntrl.ControlWheels    = true;
                            cntrl.ClearWaypoints();
                            var desiredFacing = command.GetNavData(program).desiredForward.Value;
                            cntrl.AddWaypoint(Me.CubeGrid.GridIntegerToWorld(cntrl.Position) + desiredFacing * 10000, "dummy rotation target");
                            cntrl.AddWaypoint(new MyWaypointInfo());
                            cntrl.SetAutoPilotEnabled(true);
                            Vector3 target = Me.CubeGrid.GridIntegerToWorld(cntrl.Position) + (desiredFacing * 1000);
                            program.Echo(string.Format("RC: {0:0.0} {1:0.0} {2:0.0}", target.X, target.Y, target.Z));
                        }
                        else
                        {
                            program.Echo("Can't find any control blocks");
                        }
                        shouldSetWaypoint = 50;
                    }
                    else
                    {
                        shouldSetWaypoint--;
                    }
                }
                else
                {
                    foreach (var gyro in gyros)
                    {
                        try {
                            gyro.SetValueBool("Override", true);

                            gyro.Pitch = -targetRotation.Dot(Base6Directions.GetVector(gyro.Orientation.Left)) * 60;
                            gyro.Yaw   = targetRotation.Dot(Base6Directions.GetVector(gyro.Orientation.Up)) * 60;
                            gyro.Roll  = -targetRotation.Dot(Base6Directions.GetVector(gyro.Orientation.Forward)) * 60;
                        } catch (Exception e) { program.Echo(e.StackTrace); }
                    }
                }
            }
        public void Main(string argument, UpdateType updateSource)
        {
            string[] argInfo = argument.Split(new string[] { "," }, StringSplitOptions.None);
            if (argument == "RUN")
            {
                //Check if can scan, and scan if can.
                if (cam.CanScan(rayCastDistance))
                {
                    detectedInfo = cam.Raycast(rayCastDistance);
                }
                else
                {
                    Echo("Can't scan yet!");
                }

                Echo("INITIATING");

                coordinate = Vector3D.Zero; //initating to zero value.

                Boolean found = false;
                if (detectedInfo.HitPosition != null)
                {
                    coordinate = detectedInfo.HitPosition.Value;
                    found      = true;
                }

                if (found)
                {
                    Vector3D currentCoords = rc.GetPosition();

                    //creating unit vector
                    double denominator = Math.Sqrt(Math.Pow(coordinate.X - currentCoords.X, 2)
                                                   + Math.Pow(coordinate.Y - currentCoords.Y, 2)
                                                   + Math.Pow(coordinate.Z - currentCoords.Z, 2));
                    double xMultiplier = (coordinate.X - currentCoords.X) / denominator;
                    double yMultiplier = (coordinate.Y - currentCoords.Y) / denominator;
                    double zMultiplier = (coordinate.Z - currentCoords.Z) / denominator;

                    //manipulating target coordinate with unit vector
                    coordinate.X -= finalDistFromTarget * xMultiplier;
                    coordinate.Y -= finalDistFromTarget * yMultiplier;
                    coordinate.Z -= finalDistFromTarget * zMultiplier;

                    //Setting up backward thrusters list
                    backwardThrusters = new List <IMyThrust>();

                    //Obtaining each thruster pointing backward
                    foreach (IMyThrust thruster in thrusters)
                    {
                        if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward))
                        {
                            backwardThrusters.Add(thruster);
                        }
                    }

                    //Obtaining max backward acceleration
                    MyShipMass myShipMass = rc.CalculateShipMass();
                    backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters);

                    //autopilot settings
                    rc.ClearWaypoints();
                    rc.AddWaypoint(coordinate, "AUTO DYNAMIC BRAKING SCRIPT COORDINATE");
                    rc.SetAutoPilotEnabled(true);
                    rc.SetCollisionAvoidance(false);
                    rc.SetDockingMode(false); //CHANGE??? or dont?
                    rc.FlightMode = FlightMode.OneWay;
                    rc.Direction  = Base6Directions.Direction.Forward;
                    blindMode     = false;
                }
            }
            else if (argInfo[0] == "blind".ToLower())
            {
                int     dist   = 0;
                Boolean passed = Int32.TryParse(argInfo[1], out dist);

                if (passed)
                {
                    Vector3D dir = rc.WorldMatrix.Forward;
                    coordinate    = rc.GetPosition();
                    coordinate.X += dir.X * dist;
                    coordinate.Y += dir.Y * dist;
                    coordinate.Z += dir.Z * dist;

                    Vector3D currentCoords = rc.GetPosition();

                    //Setting up backward thrusters list
                    backwardThrusters = new List <IMyThrust>();

                    //Obtaining each thruster pointing backward
                    foreach (IMyThrust thruster in thrusters)
                    {
                        if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward))
                        {
                            backwardThrusters.Add(thruster);
                        }
                    }

                    //Obtaining max backward acceleration
                    MyShipMass myShipMass = rc.CalculateShipMass();
                    backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters);

                    //autopilot settings
                    rc.ClearWaypoints();
                    rc.AddWaypoint(coordinate, "CAPTXAN'S SCRIPT COORDINATE");
                    rc.SetAutoPilotEnabled(true);
                    rc.SetCollisionAvoidance(false);
                    rc.SetDockingMode(false); //CHANGE??? or dont?
                    rc.FlightMode = FlightMode.OneWay;
                    rc.Direction  = Base6Directions.Direction.Forward;
                    blindMode     = true;
                    blindCounter  = 0;
                }
                else
                {
                    Echo("2nd parameter is not a number!");
                }
            }
            else
            {
                //User Feedback
                if (!cam.CanScan(rayCastDistance))
                {
                    float percentage = ((cam.TimeUntilScan(rayCastDistance) / 1000) / (rayCastDistance / 2000));
                    percentage = (1 - percentage) * 100;
                    Echo("Raycast is recharging " + percentage + "%");
                    if (!cam.EnableRaycast)
                    {
                        cam.EnableRaycast = true;
                    }
                }
                else
                {
                    Echo("Ready to Scan");
                    cam.EnableRaycast = false;
                }

                //Travelling CHANGE HERE FOR ENABLE / DISABLE AUTOPILOT
                if (rc.IsAutoPilotEnabled)
                {
                    travelling = true;
                    double currentDistanceFromTarget = Vector3D.Distance(coordinate, rc.GetPosition());
                    Echo("Travelling, ETA: " + (int)(currentDistanceFromTarget / rc.GetShipSpeed()) + "s");

                    //Calculating stopping distance to determine if thrusters need to be enabled.
                    Echo("Current Speed: " + (int)rc.GetShipSpeed() + "m/s");
                    Echo("Ship Speed Limit: " + rc.SpeedLimit + "m/s");
                    if (rc.GetShipSpeed() > rc.SpeedLimit - 1) //If ship at max speed
                    {
                        Vector3D currentTrajectory = Vector3D.Normalize(rc.GetPosition() - prevPosition);
                        prevPosition = rc.GetPosition();
                        Vector3D calculatedTrajectory = Vector3D.Normalize(rc.GetPosition() - coordinate);

                        double accuracyAmount;
                        if (currentDistanceFromTarget > 15000)
                        {
                            accuracyAmount = .99999;
                        }
                        else if (currentDistanceFromTarget > 5000)
                        {
                            accuracyAmount = .9999;
                        }
                        else
                        {
                            accuracyAmount = .999;
                        }

                        if (currentDistanceFromTarget * .90 > (Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) &&
                            Math.Abs(currentTrajectory.Dot(calculatedTrajectory)) > accuracyAmount)
                        {
                            foreach (IMyThrust thruster in thrusters)
                            {
                                thruster.ApplyAction("OnOff_Off");
                            }
                        }
                        else //Curr < stopp
                        {
                            foreach (IMyThrust thruster in thrusters)
                            {
                                thruster.ApplyAction("OnOff_On");
                            }
                        }
                    }

                    Echo("Blind Mode: " + blindMode);

                    if (blindMode)
                    {
                        Echo("Blind Counter: " + blindCounter);
                        Echo("Coll Avoid: " + rc.);
                        if (cam.CanScan(((Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) * 2)))
                        {
                            detectedInfo = cam.Raycast((Math.Pow(maxSpeed, 2) / (2 * backwardsAcceleration)) * 2);
                            if (detectedInfo.HitPosition != null)
                            {
                                rc.SpeedLimit = 3;
                                rc.SetCollisionAvoidance(true);
                                blindCounter = 0;
                            }
                            else
                            {
                                if (blindCounter > 500)
                                {
                                    rc.SpeedLimit = maxSpeed;
                                    rc.SetCollisionAvoidance(false);
                                    blindCounter = 0;
                                }
                                else
                                {
                                    blindCounter++;
                                }
                            }
                        }
                    }
                }
                else if (travelling)
                {
                    foreach (IMyThrust thruster in thrusters)
                    {
                        thruster.ApplyAction("OnOff_On");
                    }
                    travelling = false;
                    blindMode  = false;
                }
            }
            //Additional Arugment Commands
            if (argument == "ABORT")
            {
                rc.SetAutoPilotEnabled(false);
                rc.DampenersOverride = true;
            }
        }
예제 #19
0
        public void Main(string argument, UpdateType updateSource)
        {
            Runtime.UpdateFrequency = UpdateFrequency.Update100 | UpdateFrequency.Update10;
            IMyTextPanel     textPanel     = (IMyTextPanel)GridTerminalSystem.GetBlockWithName(lcdName);
            IMyRemoteControl remoteControl = (IMyRemoteControl)GridTerminalSystem.GetBlockWithName(remoteControllerName);

            // If setupcomplete is false, run Setup method.
            if (!setupcomplete)
            {
                Echo("Running setup.");
                Setup();
            }
            else
            {
                // To create a listener, we use IGC to access the relevant method.
                // We pass the same tag argument we used for our message.
                IGC.RegisterBroadcastListener(broadcastChannel);


                // Create a list for broadcast listeners.
                List <IMyBroadcastListener> listeners = new List <IMyBroadcastListener>();

                // The method argument below is the list we wish IGC to populate with all Listeners we've made.
                // Our Listener will be at index 0, since it's the only one we've made so far.
                IGC.GetBroadcastListeners(listeners);

                if (listeners[0].HasPendingMessage)
                {
                    // Let's create a variable for our new message.
                    // Remember, messages have the type MyIGCMessage.
                    MyIGCMessage message = new MyIGCMessage();

                    // Time to get our message from our Listener (at index 0 of our Listener list).
                    // We do this with the following method:
                    message = listeners[0].AcceptMessage();


                    // A message is a struct of 3 variables. To read the actual data,
                    // we access the Data field, convert it to type string (unboxing),
                    // and store it in the variable messagetext.
                    string messagetext = message.Data.ToString();



                    // We can also access the tag that the message was sent with.
                    string messagetag = message.Tag;

                    //Here we store the "address" to the Programmable Block (our friend's) that sent the message.
                    long sender = message.Source;

                    //Do something with the information!
                    Echo("Message received with tag" + messagetag + "\n\r");
                    Echo("from address " + sender.ToString() + ": \n\r");
                    Echo(messagetext);



                    allmessage += $"\n new message \n {messagetext}\n{messagetext.Split(':')[2]}";
                    textPanel.WriteText(allmessage);

                    List <MyWaypointInfo> myWaypoints = new List <MyWaypointInfo>();

                    string gpsname = messagetext.Split(':')[1];
                    double x       = 0;
                    double y       = 0;
                    double z       = 0;
                    try
                    {
                        x = Convert.ToDouble(messagetext.Split(':')[2]);
                        y = Convert.ToDouble(messagetext.Split(':')[3]);
                        z = Convert.ToDouble(messagetext.Split(':')[4]);
                    }
                    catch (Exception e)
                    {
                        Echo(e.Message);
                    }



                    Echo(messagetext.Split('1')[0]);

                    myWaypoints.Add(new MyWaypointInfo(gpsname, x, y, z));

                    remoteControl.ClearWaypoints();

                    remoteControl.AddWaypoint(myWaypoints[0]);

                    remoteControl.SetCollisionAvoidance(true);

                    remoteControl.SetAutoPilotEnabled(true);
                }
            }

            int textlength = textPanel.GetText().Length;

            if (textlength > 100)
            {
                allmessage = "";
            }
        }
예제 #20
0
        void Main(string argument, UpdateType updateSource)
        {
            if (updateSource == UpdateType.Update1 || updateSource == UpdateType.Update10 || updateSource == UpdateType.Update100)
            {
                // Main code
                Clock.Update();
                if (Clock.Runtime == startRuntime)
                {
                    Echo("Starting.");
                    Start();
                }
                else if (startRuntime != -1)
                {
                    Echo("Waiting to start:");
                    double sec = startDelay - Clock.GetSeconds(0);
                    Echo(sec.ToString("0.0") + 's');
                    return;
                }

                Echo("Running.");
                Detect();
                Echo("Has target: " + detected);
                Echo("Known location: " + lastEnemy.HasValue);
                Echo("Firing: " + fire);
                double secSince = Clock.GetSeconds(contactTime);
                if (secSince > 0 && secSince < timeout)
                {
                    Echo("Time since contact: " + secSince.ToString("0.00"));
                }

                double temp     = rc.GetNaturalGravity().Length();
                bool   newValue = temp > useGravityValue;
                if (newValue != useGravity)
                {
                    useGravity = newValue;
                    InitializeOrbit();
                }

                Move();
                FireState();
            }
            else if (updateSource == UpdateType.IGC)
            {
                if (helpListener != null && receiveHelpMsgs && !detected && helpListener.HasPendingMessage && !rc.IsAutoPilotEnabled)
                {
                    MyIGCMessage msg = helpListener.AcceptMessage();
                    if (msg.Data is Vector3D)
                    {
                        Vector3D pos   = (Vector3D)msg.Data;
                        double   dist2 = Vector3D.DistanceSquared(rc.GetPosition(), pos);
                        if (dist2 < replyToHelpRange * replyToHelpRange)
                        {
                            lastEnemy = null;
                            rc.SetAutoPilotEnabled(false);
                            rc.ClearWaypoints();
                            rc.AddWaypoint(new MyWaypointInfo("Enemy", pos));
                            rc.FlightMode = FlightMode.OneWay;
                            rc.SetAutoPilotEnabled(true);
                        }
                    }
                }
            }
            else
            {
                Command(argument);
            }
        }
예제 #21
0
            //Primary Generic Functions
            //==========================

            //Use For General Drone Flying:
            void RC_Manager(Vector3D TARGET, IMyRemoteControl RC, bool TURN_ONLY)
            {
                //Uses Rotation Control To Handle Max Rotational Velocity
                //---------------------------------------------------------
                if (RC.GetShipVelocities().AngularVelocity.AbsMax() > PrecisionMaxAngularVel)
                {
                    print("转动速度放缓"); RC.SetAutoPilotEnabled(false); return;
                }
                //Setup Of Common Variables
                //--------------------------------------------
                Vector3D DronePosition   = RC.GetPosition();
                Vector3D Drone_To_Target = Vector3D.Normalize(TARGET - DronePosition);
                //Override Direction Detection
                //-------------------------------
                double To_Target_Angle = Vector3D.Dot(Vector3D.Normalize(RC.GetShipVelocities().LinearVelocity), Drone_To_Target);
                double Ship_Velocity   = RC.GetShipVelocities().LinearVelocity.Length();

                //Turn Only: (Will drift ship automatically)
                //--------------------------------------------

                /*List<MyWaypointInfo> way = new List<MyWaypointInfo>();
                 *      RC.GetWaypointInfo(way);
                 *      if (way.Count>0)
                 *      {
                 *          if (way[0].Coords!= TARGET)
                 *          {
                 *              //RC.ApplyAction("AutoPilot_Off");
                 *              //RC.ClearWaypoints();
                 *          }
                 *      }*/

                if (TURN_ONLY)
                {
                    //if (way.Count <1)
                    {
                        RC.ClearWaypoints();
                        GYRO.GyroOverride = false;
                        RC.AddWaypoint(TARGET, "母船起点");
                        RC.FlightMode = FlightMode.OneWay;
                        RC.Direction  = Base6Directions.Direction.Forward;
                        RC.ApplyAction("AutoPilot_On");
                        RC.ApplyAction("CollisionAvoidance_Off");
                        RC.ControlThrusters = false;
                    }
                    return;
                }
                //Drift Cancellation Enabled:
                //-----------------------------
                if (To_Target_Angle < 0.4 && Ship_Velocity > 3)
                {
                    //Aim Gyro To Reflected Vector
                    Vector3D DRIFT_VECTOR           = Vector3D.Normalize(RC.GetShipVelocities().LinearVelocity);
                    Vector3D REFLECTED_DRIFT_VECTOR = -1 * (Vector3D.Normalize(Vector3D.Reflect(DRIFT_VECTOR, Drone_To_Target)));
                    Vector3D AIMPINGPOS             = (-1 * DRIFT_VECTOR * 500) + DronePosition;

                    //if (way.Count < 1 )
                    {
                        RC.ClearWaypoints();
                        GYRO.GyroOverride = false;
                        RC.AddWaypoint(AIMPINGPOS, "AIMPINGPOS");
                        RC.SpeedLimit = 100;
                        RC.FlightMode = FlightMode.OneWay;
                        RC.Direction  = Base6Directions.Direction.Forward;
                        RC.ApplyAction("AutoPilot_On");
                        RC.ApplyAction("CollisionAvoidance_Off");
                    }
                }

                //System Standard Operation:
                //---------------------------
                else
                {
                    //Assign To RC, Clear And Refresh Command
                    List <ITerminalAction> action = new List <ITerminalAction>();
                    RC.GetActions(action);
                    RC.ControlThrusters = true;
                    RC.ClearWaypoints();
                    GYRO.GyroOverride = false;
                    RC.AddWaypoint(TARGET, "目标");
                    RC.SpeedLimit = 100;
                    RC.FlightMode = FlightMode.OneWay;
                    RC.Direction  = Base6Directions.Direction.Forward;
                    RC.ApplyAction("AutoPilot_On");
                    RC.ApplyAction("DockingMode_Off");
                    RC.ApplyAction("CollisionAvoidance_On");
                }
            }
예제 #22
0
        public void Main(string args)
        {
            // Get Text Panels
            IMyTextPanel panel1 = GridTerminalSystem.GetBlockWithName("Donkey Panel Front 1") as IMyTextPanel;
            IMyTextPanel panel2 = GridTerminalSystem.GetBlockWithName("Donkey Panel Front 2") as IMyTextPanel;
            IMyTextPanel panel3 = GridTerminalSystem.GetBlockWithName("Donkey Panel Front 3") as IMyTextPanel;

            Echo("Screen connected: " + panel1.CustomName);
            Echo("Screen connected: " + panel2.CustomName);
            Echo("Screen connected: " + panel3.CustomName);

            // Get Sensor [0]
            List <IMySensorBlock> sensors = new List <IMySensorBlock>();

            GridTerminalSystem.GetBlocksOfType <IMySensorBlock>(sensors);
            IMySensorBlock sensor = sensors[0];

            Echo("Sensor: " + sensor.CustomName);

            // Get Remote Control [0]
            List <IMyRemoteControl> remotes = new List <IMyRemoteControl>();

            GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(remotes);
            IMyRemoteControl remote = remotes[0];

            Echo("Remote: " + remote.CustomName);


            // Main

            // Write Detection to Panel 1
            panel1.WriteText("Last detected:");
            panel1.WriteText("\n" + sensor.LastDetectedEntity.Name);
            panel1.WriteText("\n" + sensor.LastDetectedEntity.TimeStamp.ToString(), true);
            panel1.WriteText("\n" + sensor.LastDetectedEntity.Relationship.ToString(), true);
            panel1.WriteText("\n" + sensor.LastDetectedEntity.Position.ToString(), true);

            // Write Remote to Panel 2
            panel2.WriteText("Flight mode: " + remote.FlightMode);
            // Get properties
            List <ITerminalProperty> remote_props = new List <ITerminalProperty>();

            remote.GetProperties(remote_props);
            foreach (ITerminalProperty property in remote_props)
            {
                panel2.WriteText("\n" + property.Id + " : " + property.TypeName, true);
            }

            // Write Waypoints to Panel 3
            List <MyWaypointInfo> waypoints = new List <MyWaypointInfo>();

            remote.GetWaypointInfo(waypoints);
            foreach (MyWaypointInfo waypoint in waypoints)
            {
                panel2.WriteText(waypoint.Name + " - " + waypoint.Coords);
            }

            // Add waypoint
            remote.ClearWaypoints();
            remote.AddWaypoint(sensor.LastDetectedEntity.Position, sensor.LastDetectedEntity.Name + " " + sensor.LastDetectedEntity.TimeStamp);
        }
 void updateRemote(IMyRemoteControl Remote, Vector3D newPos)
 {
     Remote.ClearWaypoints();
     Remote.AddWaypoint(newPos, "Wingman Target");
     Remote.SetAutoPilotEnabled(true);
 }
예제 #24
0
        void Main()
        {
            //check if current RC is damaged, look for a replacement
            if (_currentControl == null || !_currentControl.IsFunctional)
            {
                _currentControl = _controllers.FirstOrDefault(c => c.IsFunctional);
            }

            if (_currentControl == null)
            {
                return; //no controls left :(
            }
            //Check Player Distance From Origin
            _currentControl.ClearWaypoints();
            Vector3D currentPos = _currentControl.GetPosition();
            Vector3D closestPlayer;

            _currentControl.GetNearestPlayer(out closestPlayer);

            double playerDistanceOrigin = Vector3D.DistanceSquared(closestPlayer, _origin);
            double playerDistanceDrone  = Vector3D.DistanceSquared(currentPos, closestPlayer);

            if (playerDistanceDrone < BREAKAWAY_DISTANCE * BREAKAWAY_DISTANCE || playerDistanceOrigin < PATROL_RADIUS * PATROL_RADIUS)
            {
                //Chase Player
                _currentControl.AddWaypoint(closestPlayer, "Player");

                //update guns
                if (USE_STATIC_GUNS)
                {
                    if (playerDistanceDrone <= WEAPON_ENGAGE_DIST * WEAPON_ENGAGE_DIST)
                    {
                        Vector3D playerDir = closestPlayer - currentPos;
                        playerDir.Normalize();
                        double dot = Vector3D.Dot(_currentControl.WorldMatrix.Forward, playerDir);
                        //check if player is inside our target cone
                        if (dot > _weaponAngle)
                        {
                            StartShooting();
                            _shooting = true;
                        }
                        else
                        {
                            StopShooting();
                            _shooting = false;
                        }
                    }
                    else if (playerDistanceDrone > WEAPON_DISENGAGE_DIST * WEAPON_DISENGAGE_DIST && _shooting)
                    {
                        StopShooting();
                        _shooting = false;
                    }
                }
            }
            else
            {
                //Go To Origin
                _currentControl.AddWaypoint(_origin, "Origin");
                if (_shooting && USE_STATIC_GUNS)
                {
                    _shooting = false;
                    StopShooting();
                }
            }

            _currentControl.SetAutoPilotEnabled(true);
        }
예제 #25
0
        void FollowPath(List <MyWaypointInfo> path, Boolean goingIn)
        {
            if (path.Count == 1 && !goingIn && lastReversePath)
            {
                Vector3D lastPathCoords = path.First().Coords;
                Vector3D unitVector     = Vector3D.Normalize(lastPathCoords - rc.GetPosition());
                Vector3D finalCoords    = lastPathCoords + (unitVector * finalOutDistance);
                path.Clear();
                rc.ClearWaypoints();
                MyWaypointInfo finalWaypoint = new MyWaypointInfo("FINAL", finalCoords);
                path.Add(finalWaypoint);
                rc.SetCollisionAvoidance(true);
                lastReversePath = false;
            }
            else if (path.Count != 0)
            {
                if (Vector3D.Distance(rc.GetPosition(), path.First().Coords) > 8)
                {
                    Echo("FollowPath: " + Vector3D.Distance(rc.GetPosition(), path.First().Coords));
                    if (!rc.IsAutoPilotEnabled)
                    {
                        rc.ClearWaypoints();
                        rc.AddWaypoint(path.First());
                        rc.SetCollisionAvoidance(collisionAvoidance);
                        rc.SetDockingMode(false);
                        rc.SetAutoPilotEnabled(true);
                    }
                    else if (Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) < 5)
                    {
                        path.Remove(path.First());
                        collisionAvoidance = false;
                        rc.ClearWaypoints();
                    }
                }
                else
                {
                    path.Remove(path.First());
                    collisionAvoidance = false;
                    rc.ClearWaypoints();
                }
            }
            else if (goingIn)
            {
                Dock2(dockingConnectorPos, dockingDir);
            }
            else
            {
                Storage             = "";
                dockingConnectorPos = new Vector3D();
                dockingDir          = new Vector3D();
                mode = 0;
                globalPath.Clear();
                reversePath.Clear();
                rc.ClearWaypoints();
                lastReversePath = true;

                foreach (IMyThrust thrust in allThrusters)
                {
                    thrust.ThrustOverridePercentage = 0;
                }
                foreach (IMyGyro gyro in gyros)
                {
                    gyro.GyroOverride = false;
                    gyro.Pitch        = 0;
                    gyro.Yaw          = 0;
                    gyro.Roll         = 0;
                }

                Boolean sent = antenna.TransmitMessage("freepath," + groupName);
                if (!sent)
                {
                    messageQue.Add("freepath," + groupName);
                }
                groupName = "default";

                //any ending commands here
            }
        }
            public void CommandMoveDirection(Vector3D direction)
            {
                Vector3D target = Vector3D.Transform(direction, Controller.WorldMatrix);

                Controller.AddWaypoint(target, "test target " + direction + " " + direction.ToString());
            }