private void GoTo(Vector3D pos, string label) { Stop(); rc.AddWaypoint(new MyWaypointInfo(label, pos)); rc.FlightMode = FlightMode.OneWay; rc.SetAutoPilotEnabled(true); }
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); }
//Idle Drone function void Idle() { //If Auto Home enabled then return home if not within buffer range. if (Vector3.DistanceSquared(_homeLoc, Me.GetPosition()) > distanceBuffer * distanceBuffer && autoHome) { ReturnHome(); return; } else { if (modeIndicator != null) { modeIndicator.SetValue <Color>("Color", new Color(1f, 1f, 0f)); } EchoToLCD("Status: Idle"); if (_patrolEnabled && !MissingOrDamaged()) { Patrol(); } else { StopPatrol(); ResetTargets(); //resets any target info if (_remoteBlock != null) { _remoteBlock.SetAutoPilotEnabled(false); _remoteBlock.FlightMode = FlightMode.OneWay; _remoteBlock.ClearWaypoints(); } } } }
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); }
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); }
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); } }
//Use For Precise Turning (docking, mining, attacking) //----------==--------=------------=-----------=---------------=------------=-----=-----*/ void GyroTurn6(Vector3D TARGET, double GAIN, IMyGyro GYRO, IMyRemoteControl REF_RC, double ROLLANGLE, double MAXANGULARVELOCITY) { //确保自动驾驶仪没有功能 REF_RC.SetAutoPilotEnabled(false); //检测前、上 & Pos Vector3D ShipForward = REF_RC.WorldMatrix.Forward; Vector3D ShipUp = REF_RC.WorldMatrix.Up; Vector3D ShipPos = REF_RC.GetPosition(); //创建和使用逆Quatinion Quaternion Quat_Two = Quaternion.CreateFromForwardUp(ShipForward, ShipUp); var InvQuat = Quaternion.Inverse(Quat_Two); Vector3D DirectionVector = Vector3D.Normalize(TARGET - ShipPos); //RealWorld Target Vector Vector3D RCReferenceFrameVector = Vector3D.Transform(DirectionVector, InvQuat); //Target Vector In Terms Of RC Block //转换为局部方位和高度 double ShipForwardAzimuth = 0; double ShipForwardElevation = 0; Vector3D.GetAzimuthAndElevation(RCReferenceFrameVector, out ShipForwardAzimuth, out ShipForwardElevation); //Does Some Rotations To Provide For any Gyro-Orientation做一些旋转来提供任何旋转方向 var RC_Matrix = REF_RC.WorldMatrix.GetOrientation(); var Vector = Vector3.Transform((new Vector3D(ShipForwardElevation, ShipForwardAzimuth, ROLLANGLE)), RC_Matrix); //Converts To World转换为世界 var TRANS_VECT = Vector3.Transform(Vector, Matrix.Transpose(GYRO.WorldMatrix.GetOrientation())); //Converts To Gyro Local转换为陀螺仪方位 //Applies To Scenario适用于场景 GYRO.Pitch = (float)MathHelper.Clamp((-TRANS_VECT.X * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY); GYRO.Yaw = (float)MathHelper.Clamp(((-TRANS_VECT.Y) * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY); GYRO.Roll = (float)MathHelper.Clamp(((-TRANS_VECT.Z) * GAIN), -MAXANGULARVELOCITY, MAXANGULARVELOCITY); GYRO.GyroOverride = true; //GYRO.SetValueFloat("Pitch", (float)((TRANS_VECT.X) * GAIN)); //GYRO.SetValueFloat("Yaw", (float)((-TRANS_VECT.Y) * GAIN)); //GYRO.SetValueFloat("Roll", (float)((-TRANS_VECT.Z) * GAIN)); }
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!"); }
void Target(Vector3 position) { target = position; mainControl.ClearWaypoints(); mainControl.AddWaypoint(position, "Target Destination"); mainControl.FlightMode = FlightMode.OneWay; mainControl.SetAutoPilotEnabled(true); }
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; } } }
//--------------- Pilot management --------------- public bool onUpdate() { if (remotePilot.IsAutoPilotEnabled) { if (state == PilotState.DISABLED) { state = PilotState.DRIVING; } this.Objective = getCurrentObjective(); if (this.Objective != null) { double destination = Move(); if (destination < precisionFactor) {// target reached if (state == PilotState.AVOID) { state = PilotState.DRIVING; } bool hasAny = RemoveReachedObjective(); if (!hasAny) { uIManager.printOnScreens("service", "[SYS] AP destination reached"); remotePilot.HandBrake = true; wheelController.ReleaseWheels(); } } } else { // No waypoints in list remotePilot.SetAutoPilotEnabled(false); return(false); } } else { wheelController.ReleaseWheels(); state = PilotState.DISABLED; } return(true); }
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(); } }
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; }
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); }
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 = ""; } }
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); } } } }
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); } }
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; } }
//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"); } }
public void Main(string argument, UpdateType updateType) { Vector3D homebase = new Vector3D(coord[0], coord[1], coord[2]); Vector3D homebasevelocity = new Vector3D(velocityout[0], velocityout[1], velocityout[2]); MatrixD m = brain.WorldMatrix; Matrix test; switch (argument.ToLower()) { case "auto": brain.SetAutoPilotEnabled(true); brain.SetCollisionAvoidance(true); brain.DampenersOverride = true; Echo("Auto Pilot Enabled."); break; case "stop": brain.SetAutoPilotEnabled(false); brain.SetCollisionAvoidance(false); brain.DampenersOverride = false; Echo("Auto Pilot Disabled."); break; } info.WritePublicText(""); info.WritePublicText(brain.CalculateShipMass().TotalMass.ToString() + " : Mass \n", true); //calculate manhattan distance int dist = (int)Math.Ceiling(Math.Abs(homebase.X - brain.GetPosition().X) + Math.Abs(homebase.Y - brain.GetPosition().Y) + Math.Abs(homebase.Z - brain.GetPosition().Z)); info.WritePublicText(dist.ToString() + " :Distance \n", true); //debugging to an lcd screen - used as a visual aid info.WritePublicText(m.Forward.X.ToString(), true); //found out how to use and turn gyro //if (dist < 20 && m.Forward.X < 0.1) //{ // gyro.SetValueFloat("Yaw", 2); // gyro.GetActionWithName("Override").Apply(gyro); //} //check for new homebase coords if (listeners[0].HasPendingMessage) { packet = listeners[0].AcceptMessage(); string messagetext = packet.Data.ToString(); sentcord = messagetext; } //check for new homebase velocity if (listeners[1].HasPendingMessage) { packet = listeners[1].AcceptMessage(); string messagetext1 = packet.Data.ToString(); sentvelocity = messagetext1; } string[] coords = sentcord.Split(' '); if (coords[0] != "") { coord[0] = double.Parse(coords[0].Remove(0, 2)); coord[1] = double.Parse(coords[1].Remove(0, 2)); coord[2] = double.Parse(coords[2].Remove(0, 2)); } string[] velocity = sentvelocity.Split(' '); if (velocity[0] != "") { velocityout[0] = double.Parse(velocity[0].Remove(0, 2)); velocityout[1] = double.Parse(velocity[1].Remove(0, 2)); velocityout[2] = double.Parse(velocity[2].Remove(0, 2)); } GetPredictedTargetPosition(homebase, homebasevelocity); //add new thrusters to list for (int i = 0; i < term.Count; i++) { onGridThrust.Add((IMyThrust)term[i]); } }
public void Main(string argument, UpdateType updateSource) { if (goodsetup) { Echo("LastR: " + lastReversePath); Echo("Mode: " + mode); Echo("DockingDir: " + rcDockingDir.ToString()); Echo("Password: "******"Argument: " + argument); string[] info = argument.Split(new string[] { "," }, StringSplitOptions.None); if (updateSource != UpdateType.Antenna) { if (info[0].ToLower() == "dock") { if (info.Length == 1) { Boolean sent = antenna.TransmitMessage("requestdock," + password + ",default"); if (!sent) { messageQue.Add("requestdock," + password + ",default"); } } else if (info.Length == 2) { Boolean sent = antenna.TransmitMessage("requestdock," + password + "," + info[1]); if (!sent) { messageQue.Add("requestdock," + password + "," + info[1]); } groupName = info[1]; } else if (info.Length == 3) { Boolean sent = antenna.TransmitMessage("requestdock," + password + "," + groupName + "," + info[2]); if (!sent) { messageQue.Add("requestdock," + password + "," + groupName + "," + info[2]); } } else { Echo("ERROR, ARGUMENT SIZE INVALID"); } } else if (info[0].ToLower() == "stop") { Storage = ""; dockingConnectorPos = new Vector3D(); dockingDir = new Vector3D(); mode = 0; globalPath.Clear(); reversePath.Clear(); rc.ClearWaypoints(); 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("canceldock," + password); if (!sent) { messageQue.Add("canceldock," + password); } } else if (info[0] == "depart") { if (mode == 5 && connector.Status == MyShipConnectorStatus.Connected) { Main("dock," + groupName + ",leaving", UpdateType.Mod); } else { Echo("ERROR, WRONG MODE OR ALREADY DISCONNECTED"); } } else if (info[0].ToLower() == "newpassword") { Random r = new Random(); password = r.Next(1000000, 9999999) + ""; } } else if (updateSource == UpdateType.Antenna && info[0] == password) { Echo("Message Received: " + argument); if (info[1] == "received" && info.Length == 3) //info[2] is name of spaceport { Echo("Request to '" + info[2] + "' was received, awaiting further instruction."); } else if (info[1] == "fail") { Echo("Request to '" + info[3] + "' failed."); } else if (info[1] == "rejected") { Echo("TOOK TO LONG, DOCKING PERMISSION REJECTED"); mode = 0; rc.SetAutoPilotEnabled(false); antenna.CustomName += " ERROR"; } else if (info[1] == "wait") { Echo("Request to '" + info[3] + "' success, but placed into waiting que"); waiting = true; } else if (info[1] == "dockinginfo") { if (mode == 5) { connector.Disconnect(); List <MyWaypointInfo> path = new List <MyWaypointInfo>(); string[] strWaypoints = new string[info.Length - 5]; for (int i = 0; i < strWaypoints.Length; i++) { strWaypoints[i] = info[i + 5]; } foreach (string waypoint in strWaypoints) { MyWaypointInfo newPoint; Boolean pass = MyWaypointInfo.TryParse(waypoint, out newPoint); if (pass) { path.Add(newPoint); } else { break; } } path.Reverse(); reversePath = path; EnableRC(reversePath, out path); mode = 6; } else if (info.Length == 5) { linkedConnectorName = info[2]; string strConnectorPos = info[3]; string strDockingDir = info[4]; //parse str's into their proper values Boolean pass1 = Vector3D.TryParse(strConnectorPos, out dockingConnectorPos); Boolean pass2 = Vector3D.TryParse(strDockingDir, out dockingDir); Dock2(dockingConnectorPos, dockingDir); mode = 2; } else if (info.Length > 5) { linkedConnectorName = info[2]; string strConnectorPos = info[3]; string strDockingDir = info[4]; string[] strWaypoints = new string[info.Length - 5]; for (int i = 0; i < strWaypoints.Length; i++) { strWaypoints[i] = info[i + 5]; } //parse str's into their proper values Boolean pass1 = Vector3D.TryParse(strConnectorPos, out dockingConnectorPos); Boolean pass2 = Vector3D.TryParse(strDockingDir, out dockingDir); pass2 = false; List <MyWaypointInfo> path = new List <MyWaypointInfo>(); Boolean pass3 = true; foreach (string waypoint in strWaypoints) { pass2 = true; MyWaypointInfo newPoint; pass3 = MyWaypointInfo.TryParse(waypoint, out newPoint); if (pass3) { path.Add(newPoint); } else { break; } } if (pass1 && pass2 && pass3) { EnableRC(path, out globalPath); reversePath.Reverse(); mode = 1; } else { Echo(pass1 + " " + pass2 + " " + pass3); } } } } else if (info[0] == "antennapos" && info.Length == 2) { Boolean updated = Vector3D.TryParse(info[1], out antennaPos); if (updated) { antenna.Radius = (float)(Vector3D.Distance(rc.GetPosition(), antennaPos) + 10); } else { Echo("Failed to update antenna position"); } } else if (mode == 2 && !rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) >= 5) { rc.SetAutoPilotEnabled(true); } else if (mode == 1 && globalPath.Count != 0) { FollowPath(globalPath, true); } } else if (mode == 1) { FollowPath(globalPath, true); } else if (mode == 2 && rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) < 5) { Dock3(); Boolean sent = antenna.TransmitMessage("freepath," + groupName); if (!sent) { messageQue.Add("freepath," + groupName); } } else if (mode == 2 && !rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) >= 5) { rc.SetAutoPilotEnabled(true); } else if (mode == 3 && Dock3()) { Echo("DOCKED!"); } else if (mode == 6) { FollowPath(reversePath, false); } else if (updateSource == UpdateType.Update100) { shipMass = rc.CalculateShipMass().TotalMass; } if (waiting) { Echo("Waiting for clearance"); } } else { Echo("SETUP FAILED. DO NOT SETUP WHILE CONNECTED TO ANOTHER GRID"); } }
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); } } }
void updateRemote(IMyRemoteControl Remote, Vector3D newPos) { Remote.ClearWaypoints(); Remote.AddWaypoint(newPos, "Wingman Target"); Remote.SetAutoPilotEnabled(true); }