//IMyCockpit cockpit; public Program() { control = GridTerminalSystem.GetBlockWithName("Remote Control") as IMyRemoteControl; display = GridTerminalSystem.GetBlockWithName("LCD Test") as IMyTextPanel; //cockpit = GridTerminalSystem.GetBlockWithName("Flight Seat") as IMyCockpit; }
public static void DisplayRcControls(IMyTerminalBlock block, List <IMyTerminalControl> controls) { if (block.SlimBlock.BlockDefinition.Id.TypeId != typeof(MyObjectBuilder_RemoteControl) || !Logger.CurrentDebugTypeList.Contains(DebugTypeEnum.Terminal)) { return; } //Use Block As Reference - Button var buttonA = MyAPIGateway.TerminalControls.CreateControl <IMyTerminalControlButton, IMyRemoteControl>("RAI-Debug-RC-UseAsReference"); buttonA.Enabled = (b) => { return(true); }; buttonA.Visible = (b) => { return(true); }; buttonA.Title = MyStringId.GetOrCompute("Use Block Reference"); buttonA.Tooltip = MyStringId.GetOrCompute("This button will set this block as the current reference block when calculating position offset using chat commands."); buttonA.Action = (b) => { ReferenceRemoteControl = b as IMyRemoteControl; }; controls.Add(buttonA); var buttonB = MyAPIGateway.TerminalControls.CreateControl <IMyTerminalControlButton, IMyRemoteControl>("RAI-Debug-RC-ResetAI"); buttonB.Enabled = (b) => { return(true); }; buttonB.Visible = (b) => { return(EntityWatcher.RivalAiBlockIds.Contains(b.SlimBlock.BlockDefinition.Id)); }; buttonB.Title = MyStringId.GetOrCompute("Reset AI"); buttonB.Action = (b) => { BehaviorManager.AiNeedsReset = true; lock (BehaviorManager.ResetAiBlocks) BehaviorManager.ResetAiBlocks.Add(b as IMyRemoteControl); Logger.MsgDebug("Resetting AI", DebugTypeEnum.BehaviorSetup); }; controls.Add(buttonB); }
public AdvanceControlShip(IMyCockpit cockpit) { m_shipControl = cockpit; m_cockpit = cockpit; m_remote = null; Matrix cockOrientation = new Matrix(); m_shipControl.Orientation.GetMatrix(out cockOrientation); rotation_Bcockpit_2_Bship = cockOrientation; rotation_Bship_2_Bcockpit = MatrixD.Transpose(rotation_Bcockpit_2_Bship); //Transpose is quicker than invert, and equivalent in this case if (USE_DEBUG) { lcd1 = m_cockpit.GetSurface(0); setFont(lcd1); if (m_cockpit.SurfaceCount > 1) { lcd2 = m_cockpit.GetSurface(1); setFont(lcd2); } if (m_cockpit.SurfaceCount > 2) { lcd3 = m_cockpit.GetSurface(2); setFont(lcd3); } } }
public ManeuverService(Program program, IMyRemoteControl remote, Drone drone, double DistanceAccuracy = 0.4) { this.Program = program; this.Remote = remote; this.Drone = drone; this.DistanceAccuracy = DistanceAccuracy; // Check if a Remote Control or Cockpit is found. if (this.Remote == null) { throw new Exception("No Remote Controller found."); } // Get Gyros. this.Gyros = new List <IMyGyro>(); gridRef().GetBlocksOfType(this.Gyros, gyro => gyro.IsSameConstructAs(program.Me)); if (this.Gyros == null || this.Gyros.Count == 0) { throw new Exception("No Gyros found."); } // Initialize the thrusters. InitThrusters(); // Set rotation PID controllers PitchPID = new PID(5, 0, 3, 0.75); YawPID = new PID(5, 0, 3, 0.75); RollPID = new PID(5, 0, 3, 0.75); // Set translation PID controllers XPID = new PID(2, 1, 0, 0.75); YPID = new PID(2, 1, 0, 0.75); ZPID = new PID(2, 1, 0, 0.75); }
Program() { _guns = new List <IMyUserControllableGun>(); _controllers = new List <IMyRemoteControl>(); GridTerminalSystem.GetBlocksOfType(_guns); GridTerminalSystem.GetBlocksOfType(_controllers); _currentControl = _controllers.FirstOrDefault(c => c.IsFunctional); if (_currentControl == null) { return; } if (string.IsNullOrEmpty(Storage)) { if (!Vector3D.TryParse(Storage, out _origin)) { _origin = _currentControl.GetPosition(); } } else { _origin = _currentControl.GetPosition(); Storage = _origin.ToString(); } _weaponAngle = Math.Cos(MathHelperD.ToRadians(WEAPON_ANGLE_LIMIT)); }
// This code will run on all clients and the server, so we need to isolate it to the server only. public override void Init(MyObjectBuilder_EntityBase objectBuilder) { _objectBuilder = objectBuilder; this.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; if (!_staticIsInitialized) { _staticIsInitialized = true; _initialRemoteControlMaxSpeed = (float)ConfigurableSpeedComponentLogic.Instance.EnvironmentComponent.RemoteControlMaxSpeed; } if (!_isInitilized) { // Use this space to initialize and hook up events. NOT TO PROCESS ANYTHING. _isInitilized = true; if (_initialRemoteControlMaxSpeed > 0) { _remoteControlEntity = (IMyRemoteControl)Entity; List <IMyTerminalControl> controls; MyAPIGateway.TerminalControls.GetControls <IMyRemoteControl>(out controls); //VRage.Utils.MyLog.Default.WriteLine($"#### SpeedLimit {_remoteControlEntity.SpeedLimit} {_initialRemoteControlMaxSpeed}"); IMyTerminalControl control = controls.FirstOrDefault(c => c.Id == "SpeedLimit"); IMyTerminalControlSlider sliderControl = control as IMyTerminalControlSlider; // control limits are set universally and cannot be applied individually. sliderControl?.SetLimits(0, _initialRemoteControlMaxSpeed); } } }
public DespawnSystem(IMyRemoteControl remoteControl = null) { UsePlayerDistanceTimer = true; PlayerDistanceTimerTrigger = 150; PlayerDistanceTrigger = 25000; UseNoTargetTimer = false; NoTargetTimerTrigger = 60; UseRetreatTimer = false; RetreatTimerTrigger = 600; RetreatDespawnDistance = 3000; RemoteControl = null; PlayerDistanceTimer = 0; PlayerDistance = 0; RetreatTimer = 0; NoTargetTimer = 0; DoDespawn = false; DoRetreat = false; NoTargetExpire = false; Setup(remoteControl); }
public Simulated_Targeting(IMyRemoteControl reference, Vector3D targetPosition, Vector3D projectileStartPosition, Vector3D projectileForward, double projectileAcceleration, MyDetectedEntityInfo planet, double surfaceGravity, double projectileSpeed = 100, double projectileSpeedCap = 104.75, double planetRadiusOverride = 0) { this.reference = reference; this.targetPosition = targetPosition; this.projectileSpeed = projectileSpeed; this.projectileSpeedCap = projectileSpeedCap; this.projectileStartPosition = projectileStartPosition; this.planet = planet; this.surfaceGravity = surfaceGravity; this.projectileForward = projectileForward; this.projectileAcceleration = projectileAcceleration; if (planetRadiusOverride != 0) { planetRadius = planetRadiusOverride; } else { planetRadius = planet.BoundingBox.Size.X / 1.12 / 2; } GravityCutoffHeight = (Math.Pow(surfaceGravity, 1.0 / 7.0) * (planetRadius * 1.12)) / Math.Pow(0.3924, 1.0 / 7.0); gravitySphere = new BoundingSphereD(planet.Position, GravityCutoffHeight); planetSphere = new BoundingSphereD(planet.Position, (targetPosition - planet.Position).Length()); Coroutine = TargetingRoutine(); }
public void CoreSetup(IMyRemoteControl remoteControl) { Logger.MsgDebug("Beginning Core Setup On Remote Control", DebugTypeEnum.BehaviorSetup); if (remoteControl == null) { Logger.MsgDebug("Core Setup Failed on Non-Existing Remote Control", DebugTypeEnum.BehaviorSetup); SetupFailed = true; return; } if (this.ConfigCheck == false) { this.ConfigCheck = true; var valA = RAI_SessionCore.ConfigInstance.Contains(Encoding.UTF8.GetString(Convert.FromBase64String("MTk1NzU4Mjc1OQ=="))); var valB = RAI_SessionCore.ConfigInstance.Contains(Encoding.UTF8.GetString(Convert.FromBase64String("MjA0MzU0MzkyNQ=="))); if (RAI_SessionCore.ConfigInstance.Contains(Encoding.UTF8.GetString(Convert.FromBase64String("LnNibQ=="))) && (!valA && !valB)) { this.BehaviorTerminated = true; return; } } Logger.MsgDebug("Verifying if Remote Control is Functional and Has Physics", DebugTypeEnum.BehaviorSetup); this.RemoteControl = remoteControl; this.CubeGrid = remoteControl.SlimBlock.CubeGrid; this.RemoteControl.OnClosing += (e) => { this.IsEntityClosed = true; }; this.RemoteControl.IsWorkingChanged += RemoteIsWorking; RemoteIsWorking(this.RemoteControl); this.RemoteControl.OnClosing += RemoteIsClosing; this.CubeGrid.OnPhysicsChanged += PhysicsValidCheck; PhysicsValidCheck(this.CubeGrid); this.CubeGrid.OnMarkForClose += GridIsClosing; Logger.MsgDebug("Remote Control Working: " + IsWorking.ToString(), DebugTypeEnum.BehaviorSetup); Logger.MsgDebug("Remote Control Has Physics: " + PhysicsValid.ToString(), DebugTypeEnum.BehaviorSetup); Logger.MsgDebug("Setting Up Subsystems", DebugTypeEnum.BehaviorSetup); NewAutoPilot = new NewAutoPilotSystem(remoteControl, this); Broadcast = new BroadcastSystem(remoteControl); Damage = new DamageSystem(remoteControl); Despawn = new DespawnSystem(remoteControl); Extras = new ExtrasSystem(remoteControl); Owner = new OwnerSystem(remoteControl); Spawning = new SpawningSystem(remoteControl); Settings = new StoredSettings(); Trigger = new TriggerSystem(remoteControl); Logger.MsgDebug("Setting Up Subsystem References", DebugTypeEnum.BehaviorSetup); NewAutoPilot.SetupReferences(this, Settings, Trigger); Damage.SetupReferences(this.Trigger); Damage.IsRemoteWorking += () => { return(IsWorking && PhysicsValid); }; Trigger.SetupReferences(this.NewAutoPilot, this.Broadcast, this.Despawn, this.Extras, this.Owner, this.Settings, this); }
// int CowntDown=5; // bool StartCountDown =false; public Torpedo(string GroupName) { Name = GroupName; List <IMyTerminalBlock> templist = new List <IMyTerminalBlock>(); templist.Clear(); gts.GetBlocksOfType <IMyShipConnector>(templist, (b) => b.CustomName.Contains(GroupName)); merge = templist[0] as IMyShipConnector; if (merge.Status == MyShipConnectorStatus.Connectable) { merge.ToggleConnect(); } templist.Clear(); gts.GetBlocksOfType <IMyRemoteControl>(templist, (b) => b.CustomName.Contains(GroupName)); remcon = templist[0] as IMyRemoteControl; batteries = new List <IMyBatteryBlock>(); gts.GetBlocksOfType <IMyBatteryBlock>(batteries, (b) => b.CustomName.Contains(GroupName)); foreach (IMyBatteryBlock battery in batteries) { battery.Enabled = true; } thrusters = new List <IMyThrust>(); gts.GetBlocksOfType <IMyThrust>(thrusters, (b) => b.CustomName.Contains(GroupName)); gyros = new List <IMyGyro>(); gts.GetBlocksOfType <IMyGyro>(gyros, (b) => b.CustomName.Contains(GroupName)); warheads = new List <IMyWarhead>(); gts.GetBlocksOfType <IMyWarhead>(warheads, (b) => b.CustomName.Contains(GroupName)); decoys = new List <IMyDecoy>(); gts.GetBlocksOfType <IMyDecoy>(decoys, (b) => b.CustomName.Contains(GroupName)); status = 1; }
public CoreBehavior() { RemoteControl = null; CubeGrid = null; Mode = BehaviorMode.Init; PreviousMode = BehaviorMode.Init; SetupCompleted = false; SetupFailed = false; ConfigCheck = false; BehaviorTerminated = false; _despawnCheckTimer = MyAPIGateway.Session.GameDateTime; _behaviorRunTimer = MyAPIGateway.Session.GameDateTime; _settingSaveCounter = 0; _settingSaveCounterTrigger = 5; _triggerStorageKey = new Guid("8470FBC9-1B64-4603-AB75-ABB2CD28AA02"); _settingsStorageKey = new Guid("FF814A67-AEC3-4DF0-ADC4-A9B239FA954F"); _readyToSaveSettings = false; _settingsDataPending = ""; IsWorking = false; PhysicsValid = false; CoreCounter = 0; }
public GyroscopeProfile(IMyTerminalBlock block, IMyRemoteControl remoteControl, IBehavior behavior) { Block = block as IMyGyro; RemoteControl = remoteControl; Behavior = behavior; EnableOverride = false; RawValues = Vector3D.Zero; RefMatrix = MatrixD.Identity; Yaw = 0; Pitch = 0; Roll = 0; Valid = true; Block.OnClosing += CloseEntity; Block.IsWorkingChanged += WorkingChange; WorkingChange(Block); if (Working) { /* * Block.GyroOverride = false; * Block.Yaw = 0; * Block.Pitch = 0; * Block.Roll = 0; */ } }
public TP(ushort id, SubP p) : base(id, p) { loopturn = false; NormWhAng = 35; Tangle = 0; switchingsusp = false; SuspensionMode = SuspensionModes.sport; DriveMode = DriveModes.full; FirstStr = ""; SecondStr = ""; Wheels = new List <IMyMotorSuspension>(); if ( (DriverLCD = OS.GTS.GetBlockWithName("Screen Driver") as IMyTextPanel) == null || (WheelLF = OS.GTS.GetBlockWithName("Wheel Suspension 3x3 LF") as IMyMotorSuspension) == null || (WheelRF = OS.GTS.GetBlockWithName("Wheel Suspension 3x3 RF") as IMyMotorSuspension) == null || (WheelLB = OS.GTS.GetBlockWithName("Wheel Suspension 3x3 LB") as IMyMotorSuspension) == null || (WheelRB = OS.GTS.GetBlockWithName("Wheel Suspension 3x3 RB") as IMyMotorSuspension) == null || (RemoteDriver = OS.GTS.GetBlockWithName("Control car") as IMyRemoteControl) == null || (RotorRull = OS.GTS.GetBlockWithName("Rotor rull") as IMyMotorStator) == null ) { Terminate("Kontur blocks not found."); return; } Wheels = new List <IMyMotorSuspension>() { WheelLF, WheelRF, WheelLB, WheelRB }; string saved = DriverLCD.GetText(); if (string.IsNullOrEmpty(saved)) { if (saved.Contains("front")) { DriveMode = DriveModes.front; } else if (saved.Contains("rear")) { DriveMode = DriveModes.rear; } if (saved.Contains("off-road")) { SuspensionMode = SuspensionModes.offroad; } if (saved.Contains("looper")) { loopturn = true; } } ChangeFirst(); AddAct(ref MA, Main, 1); SetCmd(new Dictionary <string, Cmd> { { "sdm", new Cmd(CmdSDM, "Switch drive mode Full/Front/Rear.") }, { "ssm", new Cmd(CmdSSM, "Switch suspension mode Sport/Off road.") }, { "sl", new Cmd(CmdSL, "Switch loopturn mode.") } }); }
public StaticWeaponProfile(IMyRemoteControl remoteControl, IMyTerminalBlock block) : base(remoteControl, block) { _staticWeaponBlock = block as IMyUserControllableGun; IsStatic = true; if (_staticWeaponBlock != null) { _gunBase = (IMyGunObject <MyGunBase>)_staticWeaponBlock; } else { _weaponValid = false; } if (!_weaponValid) { return; } if (_remoteControl.WorldMatrix.Forward == _staticWeaponBlock.WorldMatrix.Forward) { _isForwardFacingWeapon = true; } GetWeaponDefinition(_staticWeaponBlock); }
public void LookAt(Vector3D target, IMyGyro gyro, IMyRemoteControl control) { Vector3D offet = (target - control.GetPosition()); if (offet.Length() < 100.0f) { ApplyGyro(Vector3.Zero); return; } Vector3 direction = Vector3D.Normalize(offet); if (spaceship.gravity.LengthSquared() > 1e-1f) { Allign(direction, spaceship.gravity, gyro, control); } else { Quaternion quat = Quaternion.CreateFromForwardUp(control.WorldMatrix.Forward, control.WorldMatrix.Up); quat.Conjugate(); direction = quat * direction; Vector3.GetAzimuthAndElevation(direction, out azimuth, out elevation); Vector3 final = Vector3.Transform(new Vector3(elevation, azimuth, 0.0f), control.WorldMatrix.GetOrientation() * Matrix.Transpose(gyro.WorldMatrix.GetOrientation())); ApplyGyro(-final); } }
//IMyGridProgramRuntimeInfo runtimeInfo = null; public Program() //constructor is called when you "compile" script ingame { deltaT = Runtime.TimeSinceLastRun.TotalSeconds; //runtimeInfo.TimeSinceLastRun.TotalSeconds; List <IMyRemoteControl> controllers = new List <IMyRemoteControl>(); GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(controllers); controller = controllers[0];//lazilly assuming 1 RC for now List <IMyRadioAntenna> antennas = new List <IMyRadioAntenna>(); GridTerminalSystem.GetBlocksOfType <IMyRadioAntenna>(antennas); antenna = antennas[0]; thrusters = new List <IMyThrust>(); GridTerminalSystem.GetBlocksOfType <IMyThrust>(thrusters); maxTotalEffectiveThrust = 0.0f; numThrusters = thrusters.Count; freefallThreshold = 10.0f; craftHeight = 5.0f; touchdownHeight = craftHeight + 1;//adding wiggle room because craft tends to bounce and code the inputs don't always capture that stage = 0; Storage = stage + ";";; Echo($"Code Initialized"); Runtime.UpdateFrequency = UpdateFrequency.Update1;//once run, this script needs to control the craft actively }
public CollisionSystem(IMyRemoteControl remoteControl, AutoPilotSystem autoPilot) { if (remoteControl == null || !MyAPIGateway.Entities.Exist(remoteControl?.SlimBlock?.CubeGrid)) { return; } UseCollisionDetection = true; RemoteControl = remoteControl; Matrix = MatrixD.Identity; Velocity = Vector3D.Zero; Owner = 0; AutoPilot = autoPilot; VelocityResult = new CollisionResult(this, Direction.None); TargetResult = new CollisionResult(this, Direction.None); ForwardResult = new CollisionResult(this, Direction.Forward); BackwardResult = new CollisionResult(this, Direction.Backward); UpResult = new CollisionResult(this, Direction.Up); DownResult = new CollisionResult(this, Direction.Down); LeftResult = new CollisionResult(this, Direction.Left); RightResult = new CollisionResult(this, Direction.Right); }
public void Main(string argument, UpdateType updateSource) { GridTerminalSystem.GetBlocksOfType <IMyGyro>(gyros); GridTerminalSystem.GetBlocksOfType <IMyRemoteControl>(controllers); GridTerminalSystem.GetBlocksOfType <IMySensorBlock>(sensors); if (controllers.Count < 1 || gyros.Count < 1) { Echo("ERROR: either no controller or gyro"); return; } IMyRemoteControl controller = controllers[0];// //Vector2 yawAndRoll = controller.RotationIndicator; //Vector3 inputRotationVector = new Vector3(-yawAndRoll.X, yawAndRoll.Y, controller.RollIndicator);//pitch, yaw, roll. What?? ok. IMySensorBlock sensor = sensors[0]; //Echo($"{sensor.LastDetectedEntity.Position}\n{sensor.LastDetectedEntity.Orientation}\n{sensor.LastDetectedEntity.Velocity}"); //direction to the target Vector3D p1 = controller.GetPosition(); Vector3D p2 = sensor.LastDetectedEntity.Position; Vector3D p3 = p2 - p1; //rotation to the target p3.Normalize(); Vector3D heading = controller.WorldMatrix.Forward; heading.Normalize(); double angle = Math.Acos(heading.Dot(p3));//this doesn't account for up vector for now Echo($"ANGLE:{angle}"); Echo($"p3:{p3}"); antenna.HudText = angle.ToString(); //axis of rotation Vector3D cross = heading.Cross(p3); //var relativeRotation = Vector3D.Transform(cross, controller.WorldMatrix); double yaw; double pitch; GetRotationAngles(p3, controller.WorldMatrix.Forward, controller.WorldMatrix.Left, controller.WorldMatrix.Up, out yaw, out pitch); applyRotation(VECTOR@, gyros, controller); //turn axis into ship coordinates //calc the new matrix after that rotation //IF there is a gravity //calc angle to rotate by and axis of rotation, add that rotation to the rotation already underway //align the grav and up vector into the same plane...? //calc what my desired forward vector is(p3?), then //need to rotate and project up vector in line with art/nat gravity //Vector3D projection = a.Dot(b) / b.LengthSquared() * b; //applyRotation(inputRotationVector, gyros, controller); //keep this at the end previousShipVelicities = controllers[0].GetShipVelocities(); }
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); } }
internal TurretSingleAxis(IMyRemoteControl remoteControl, IMyCubeGrid rotorMountedGrid, IMyMotorStator rotor) { this.remoteControl = remoteControl; this.rotorMountedGrid = rotorMountedGrid; this.rotor = rotor; // position = rotorMountedGrid.GetPosition(); }
int RayCastShip(IMyRemoteControl control) { int output = -1; GetShipPredictedPosition(TargetInfo.Position, TargetInfo.Velocity, ticks); if (predictedPositionAngles.X * 1.1 < visor.AvailableScanRange) { //MyDetectedEntityInfo temp = visor.Raycast(predictedPositionAngles.X, predictedPositionAngles.Z, predictedPositionAngles.Y); For better Detecting... not working btw MyDetectedEntityInfo temp = visor.Raycast(predictedPosition); if (temp.IsEmpty()) { targetFound = false; //TODO Suche nach ziel einleiten } else { TargetInfo = temp; targetFound = true; predictedPositionAngles = ToLocalSpherical(TargetInfo.Position, control); } output = ticks; ticks = 1; } else { ticks++; } return(output); }
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!"); }
public ThrusterManager(string ThrustersType, Spaceship spaceship, IMyRemoteControl control, IMyGridTerminalSystem GridTerminalSystem) { this.ThrustersType = ThrustersType; this.spaceship = spaceship; ClearThrusters(); SetupThrusters(ThrustersType, control, GridTerminalSystem); }
public void SetupThrusters(string ThrustersType, IMyRemoteControl control, IMyGridTerminalSystem system) { int[] thrusters_per_direction = new int[6]; foreach (IMyThrust thruster in FindBlocksOfType <IMyThrust>(system, spaceship)) { if (thruster.CubeGrid == spaceship.cpu.CubeGrid && thruster.BlockDefinition.SubtypeName.Contains(ThrustersType)) { ManagedThruster managed = new ManagedThruster(); managed.direction = Vector3D.Transform(thruster.WorldMatrix.Backward, Matrix.Transpose(control.WorldMatrix.GetOrientation())); managed.thruster = thruster; managed.direction_type = GetThrusterDirectionType(managed.direction); thrusters_per_direction[(int)managed.direction_type]++; thrusters.Add(managed); } } thrusters.Sort((left, right) => left.direction_type.CompareTo(right.direction_type)); foreach (ManagedThruster thruster in thrusters) { thruster.power = 1.0f / (float)thrusters_per_direction[(int)thruster.direction_type]; } }
public SpawningSystem(IMyRemoteControl remoteControl) { UseSpawningSystem = false; SpawnGroups = new List <string>(); SpawnFactionOverride = new List <string>(); MinTimeBetweenSpawns = 120; MaxTimeBetweenSpawns = 300; MaxNumberOfSpawnEvents = 5; SpawnPositioning = SpawnPositioningEnum.RandomDirection; MinSpawnDistance = 300; MaxSpawnDistance = 500; SpawnVelocity = 0; SpawnOffsetPosition = Vector3D.Zero; IgnoreSpawningSafetyChecks = false; RemoteControl = remoteControl; Rnd = new Random(); LastSpawnTime = MyAPIGateway.Session.GameDateTime; ForceSpawn = false; TimeUntilNextSpawn = Rnd.Next(MinTimeBetweenSpawns, MaxTimeBetweenSpawns); TotalSpawnEvents = 0; SpawnInProgress = false; SelectedSpawnGroup = ""; SelectedFactionOverride = ""; SpawnCoords = Vector3D.Zero; SafeToSpawn = false; }
//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)); }
public Program() { gyroList = new List <IMyGyro>(); GridTerminalSystem.GetBlocksOfType <IMyGyro>(gyroList); RemCon = GridTerminalSystem.GetBlockWithName("RemCon") as IMyRemoteControl; Runtime.UpdateFrequency = UpdateFrequency.Update1; }
void Start() { gridSystem = GridTerminalSystem; gridId = Me.CubeGrid.EntityId; if (string.IsNullOrWhiteSpace(turretGroup)) { turrets = GetBlocks <IMyLargeTurretBase>(useSubgrids); } else { turrets = GetBlocks <IMyLargeTurretBase>(turretGroup, useSubgrids); } wcTurrets = new WcPbApi(); if (string.IsNullOrWhiteSpace(rcName)) { rc = GetBlock <IMyRemoteControl>(); } else { rc = GetBlock <IMyRemoteControl>(rcName, useSubgrids); } if (rc == null) { throw new Exception("Remote control block not found."); } origin = rc.GetPosition(); if (receiveHelpMsgs) { helpListener = IGC.RegisterBroadcastListener("AttackDrone_" + commsId); helpListener.SetMessageCallback(""); } startRuntime = -1; }
public static void ChangeReputationWithPlayersInRadius(IMyRemoteControl remoteControl, double radius, List <int> amounts, List <string> factions, bool applyReputationChangeToFactionMembers) { if (amounts.Count != factions.Count) { Logger.MsgDebug("Could Not Do Reputation Change. Faction Tag and Rep Amount Counts Do Not Match"); return; } var playerList = new List <IMyPlayer>(); var playerIds = new List <long>(); MyAPIGateway.Players.GetPlayers(playerList); foreach (var player in playerList) { if (player.IsBot == true) { continue; } if (Vector3D.Distance(player.GetPosition(), remoteControl.GetPosition()) > radius) { continue; } if (player.IdentityId != 0 && !playerIds.Contains(player.IdentityId)) { playerIds.Add(player.IdentityId); } } ChangePlayerReputationWithFactions(amounts, playerIds, factions, applyReputationChangeToFactionMembers); }
public ProgramRayCastTest() { Runtime.UpdateFrequency = UpdateFrequency.Update10; _camera1 = GridTerminalSystem.GetBlockWithName("camera1") as IMyCameraBlock; _remote = GridTerminalSystem.GetBlockWithName("remote1") as IMyRemoteControl; _camera1.EnableRaycast = true; }
public void PerformSelfDiagnostic() { IMyGridTerminalSystem GridTerminalSystem = MyInstance.GridTerminalSystem; if (CTRL != null && GridTerminalSystem.GetBlockWithId(this.CTRL.EntityId) == null) { CTRL = null; } if (XROT != null && GridTerminalSystem.GetBlockWithId(this.XROT.EntityId) == null) { XROT = null; } if (YROT != null && GridTerminalSystem.GetBlockWithId(this.YROT.EntityId) == null) { YROT = null; } if (YROTA != null && GridTerminalSystem.GetBlockWithId(this.YROTA.EntityId) == null) { YROTA = null; } if (RLDCon != null && GridTerminalSystem.GetBlockWithId(this.RLDCon.EntityId) == null) { RLDCon = null; } if (BSDCon != null && GridTerminalSystem.GetBlockWithId(this.BSDCon.EntityId) == null) { BSDCon = null; } if (Camera != null && GridTerminalSystem.GetBlockWithId(this.Camera.EntityId) == null) { Camera = null; } }
private void init() { #region initialization oldPBName = Me.CustomName; unique_id = (new Random()).Next(); all_blocks_found = true; autopilot_en = true; location_name = "UNKNOWN"; // For spinner counter = 0; string parse = Me.CustomName.Replace(BLOCK_PREFIX, ""); int id1 = Me.CustomName.IndexOf('['); int id2 = Me.CustomName.IndexOf(']'); if (id1 >= 0 && id2 >= 0) { parse = parse.Substring(id1 + 1, id2 - id1 - 1); } else { parse = ""; } BaconArgs Args = BaconArgs.parse(parse); IS_BASE = (Args.getFlag('b') > 0); DOCK_LEFT = (Args.getFlag('l') > 0); IS_PLANET = (Args.getFlag('p') > 0); if (IS_PLANET) IS_BASE = true; List<string> nameArg = Args.getOption("name"); if (nameArg.Count > 0 && nameArg[0] != null) { location_name = nameArg[0]; } // Set all known blocks to null or clear lists lcdPanel = null; messageReceiver = null; WANProgram = null; connector = null; remoteControl = null; door = null; timer = null; landLight = null; mainGear = 0; gyros.Clear(); destinations.Clear(); gears.Clear(); // Get all blocks List<IMyTerminalBlock> blks = new List<IMyTerminalBlock>(); GridTerminalSystem.SearchBlocksOfName(BLOCK_PREFIX, blks, hasPrefix); num_blocks_found = blks.Count; // Assign blocks to variables as appropriate foreach (var blk in blks) { // LCD panel for printing if (blk is IMyTextPanel) { lcdPanel = blk as IMyTextPanel; lcdPanel.ShowPublicTextOnScreen(); lcdPanel.SetValueFloat("FontSize", 1.2f); } // Wico Area Network programmable block else if (blk is IMyProgrammableBlock && !blk.Equals(Me)) { WANProgram = blk as IMyProgrammableBlock; } // Autopilot else if (!IS_BASE && blk is IMyRemoteControl) { remoteControl = blk as IMyRemoteControl; } /* Ship or station connector for docking * Used to connect to station and for orientation info */ else if (!IS_PLANET && blk is IMyShipConnector) { connector = blk as IMyShipConnector; } /* Door used for docking; used for orientation information * since it's more obvious which way a door faces than a connector */ else if (!IS_PLANET && blk is IMyDoor) { door = blk as IMyDoor; } // Gyros for ship orientation else if (!IS_BASE && blk is IMyGyro) { IMyGyro g = blk as IMyGyro; gyros.Add(g); } // Timer block so that we can orient ship properly - requires multiple calls/sec else if (!IS_BASE && blk is IMyTimerBlock) { timer = blk as IMyTimerBlock; timer.SetValueFloat("TriggerDelay", 1.0f); } // Light (interior or spotlight) determines where we will land else if (IS_BASE && IS_PLANET && blk is IMyInteriorLight) { landLight = blk as IMyInteriorLight; } // Landing gear.... else if (!IS_BASE && blk is IMyLandingGear) { IMyLandingGear gear = blk as IMyLandingGear; gears.Add(gear); if (gear.CustomName.ToLower().Contains("main")) { mainGear = gears.Count - 1; } } } // Make sure all gyros reset resetGyros(); // Clear block list blks.Clear(); // Get text panel blocks used by Wico Area Network for communication GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(blks, hasWANRPrefix); if (blks.Count == 0) { Echo("Error: Can't find message received text panel for Wico Area Network"); all_blocks_found = false; } else { messageReceiver = blks[0] as IMyTextPanel; messageReceiver.WritePublicTitle(""); messageReceiver.WritePrivateTitle("NAV"); } if (WANProgram == null) { Echo("Error: Can't find programming block for Wico Area Network"); all_blocks_found = false; } if (lcdPanel == null) { Echo("Error: Expect 1 LCD"); all_blocks_found = false; } if (!IS_PLANET && connector == null) { Echo("Error: Can't find any connectors to use for docking"); all_blocks_found = false; } if (!IS_BASE && remoteControl == null) { Echo("Error: Can't find any remote control blocks"); all_blocks_found = false; } if (!IS_PLANET && door == null) { Echo("Error: Can't find door"); all_blocks_found = false; } if (!IS_BASE && gyros.Count == 0) { Echo("Error: No gyros detected"); all_blocks_found = false; } if (!IS_BASE && timer == null) { Echo("Error: No timer found"); all_blocks_found = false; } if (IS_PLANET && landLight == null) { Echo("Error: No light for landing ship destination found"); all_blocks_found = false; } if (!IS_BASE && gears.Count == 0) { Echo("Warning: no landing gear found. You will not be able to land on planets"); } // Init communicator state machine comm = communicate().GetEnumerator(); // Clear autopilot state machine fly = null; #endregion }
private void FindCmdLine() { if (Ship == null || cmdline != null) return; IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(Ship); List<Sandbox.ModAPI.Ingame.IMyTerminalBlock> T = new List<Sandbox.ModAPI.Ingame.IMyTerminalBlock>(); gridTerminal.GetBlocksOfType<IMyTerminalBlock>(T); cmdline = T.FirstOrDefault(x => (x).CustomName.Contains("#PlayerDrone#")) as IMyRemoteControl; }
public AutoHoverController(IMyGridTerminalSystem gts, IMyProgrammableBlock pb) { Me = pb; GridTerminalSystem = gts; remote = GridTerminalSystem.GetBlockWithName(RemoteControlName) as IMyRemoteControl; gyro = GridTerminalSystem.GetBlockWithName(GyroName) as IMyGyro; if (!String.IsNullOrEmpty(TextPanelName)) screen = GridTerminalSystem.GetBlockWithName(TextPanelName) as IMyTextPanel; var list = new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType<IMyGyro>(list, x => x.CubeGrid == Me.CubeGrid && x != gyro); gyros = list.ConvertAll(x => (IMyGyro)x); gyros.Insert(0, gyro); gyros = gyros.GetRange(0, GyroCount); mode = "Hover"; setSpeed = 0; }