public PlayerData get(IMyPlayer player) { PlayerData result; if(!mPlayerData.TryGetValue(player.SteamUserId , out result)) { result = new PlayerData(player.SteamUserId); mPlayerData.Add(player.SteamUserId , result); } return result; }
public static void Smite(IMyPlayer selectedPlayer) { var worldMatrix = selectedPlayer.Controller.ControlledEntity.GetHeadMatrix(true, true, true); var maxspeed = MyDefinitionManager.Static.EnvironmentDefinition.SmallShipMaxSpeed * 1.25f; var meteorBuilder = new MyObjectBuilder_Meteor { Item = new MyObjectBuilder_InventoryItem { Amount = 1, Content = new MyObjectBuilder_Ore { SubtypeName = CommandPlayerSmite.Instance._defaultOreName } }, PersistentFlags = MyPersistentEntityFlags2.InScene, // Very important PositionAndOrientation = new MyPositionAndOrientation { Position = (worldMatrix.Translation + worldMatrix.Up * -0.5f).ToSerializableVector3D(), Forward = worldMatrix.Forward.ToSerializableVector3(), Up = worldMatrix.Up.ToSerializableVector3(), }, LinearVelocity = worldMatrix.Down * -maxspeed, // has to be faster than JetPack speed, otherwise it could be avoided. // Update 01.052 seemed to have flipped the direction. It's Up instead of Down??? Integrity = 1 }; meteorBuilder.CreateAndSyncEntity(); }
/// <summary> /// Damages the player by specified amount /// </summary> /// <param name="player"></param> /// <param name="amount"></param> public void Hurt(IMyPlayer player, float amount) => player.Character.DoDamage(amount, MyDamageType.Unknown, true);
private void CheckPlayerInDockingZone(IMyPlayer player) { if(player.Controller == null || player.Controller.ControlledEntity == null || player.Controller.ControlledEntity.Entity == null) return; IMyEntity entity = player.Controller.ControlledEntity.Entity; long playerId = player.PlayerID; IMyEntity parent = entity.GetTopMostParent(); // Not a ship? let's not process if (!(parent is IMyCubeGrid)) { if (m_playersInside.Contains(playerId)) { m_playersInside.Remove(playerId); ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId); Communication.Notification(steamId, MyFontEnum.DarkBlue, 7, "You have exited a ship in a docking zone"); } return; } // Get All ships with 500m BoundingSphereD sphere = new BoundingSphereD(parent.GetPosition(), 500); List<IMyEntity> nearByEntities = null; // Live dangerously (no wrapper for speed!) try { nearByEntities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); } catch(Exception ex) { Logging.WriteLineAndConsole(string.Format("CheckPlayerInDockingZone(): {0}", ex.ToString())); return; } if (nearByEntities == null) return; List<IMyEntity> nearByGrids = nearByEntities.FindAll(x => x is IMyCubeGrid); // See if player's ship is inside a docking zone foreach (IMyEntity nearByEntity in nearByGrids) { // Sanity Check if (!(nearByEntity is IMyCubeGrid)) return; IMyCubeGrid cubeGrid = (IMyCubeGrid)nearByEntity; // Does this grid contain a docking zone? if (m_zoneCache.Contains(cubeGrid)) { Dictionary<String, List<IMyCubeBlock>> zoneList = DockingZone.GetZonesInGrid(cubeGrid); if (zoneList == null) continue; // Get zones foreach (KeyValuePair<String, List<IMyCubeBlock>> p in zoneList) { // Check if we're inside if (DockingZone.IsGridInside((IMyCubeGrid)parent, p.Value)) { if (!m_playersInside.Contains(playerId)) { m_playersInside.Add(playerId); ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId); Communication.Notification(steamId, MyFontEnum.Green, 7, string.Format("You are inside a valid docking zone: {0}", p.Key)); } return; } } } } // We've left if (m_playersInside.Contains(playerId)) { m_playersInside.Remove(playerId); ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId); Communication.Notification(steamId, MyFontEnum.Red, 7, "You have left a docking zone"); } }
void SendPrivateMessage(IMyPlayer receiver, string message) { if (string.IsNullOrEmpty(message)) MyAPIGateway.Utilities.ShowMessage("PM System", "Message too short."); var data = new Dictionary<string, string>(); data.Add(ConnectionHelper.ConnectionKeys.ChatReceiver, receiver.SteamUserId.ToString()); data.Add(ConnectionHelper.ConnectionKeys.ChatSender, MyAPIGateway.Session.Player.SteamUserId.ToString()); data.Add(ConnectionHelper.ConnectionKeys.ChatSenderName, MyAPIGateway.Session.Player.DisplayName); data.Add(ConnectionHelper.ConnectionKeys.ChatMessage, message); string messageData = ConnectionHelper.ConvertData(data); ConnectionHelper.SendMessageToServer(ConnectionHelper.ConnectionKeys.PrivateMessage, messageData); MyAPIGateway.Utilities.ShowMessage(string.Format("Whispered {0}", receiver.DisplayName), message); }
/// <summary> /// Any player who owns a block on the grid can modify it. If noone owns a block everyone can modify it. /// </summary> /// <param name="player"></param> /// <param name="cubeGrid"></param> /// <returns></returns> public static bool CanModify(IMyPlayer player, Sandbox.ModAPI.IMyCubeGrid cubeGrid) { var allSmallOwners = cubeGrid.GetAllSmallOwners(); return allSmallOwners.Count == 0 || allSmallOwners.Contains(player.IdentityId); }
private void ThrowBomb(IMyPlayer player) { if (player == null) return; MatrixD worldMatrix; Vector3D position; if (player.Controller.ControlledEntity.Entity.Parent == null) { worldMatrix = player.Controller.ControlledEntity.GetHeadMatrix(true, true, false); // dead center of player cross hairs. position = worldMatrix.Translation + worldMatrix.Forward * 2.5f; // Spawn item 1.5m in front of player for safety. } else { worldMatrix = player.Controller.ControlledEntity.Entity.WorldMatrix; position = worldMatrix.Translation + worldMatrix.Forward * 2.5f + worldMatrix.Up * 0.5f; // Spawn item 1.5m in front of player in cockpit for safety. } // TODO: multiply vector against current entity.LinearVelocity. Vector3 vector = worldMatrix.Forward * 300; var gridObjectBuilder = new MyObjectBuilder_CubeGrid() { PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene, GridSizeEnum = MyCubeSize.Large, IsStatic = false, LinearVelocity = vector, AngularVelocity = new SerializableVector3(0, 0, 0), PositionAndOrientation = new MyPositionAndOrientation(position, Vector3.Forward, Vector3.Up), DisplayName = "Prepare to die." }; MyObjectBuilder_Warhead cube = new MyObjectBuilder_Warhead() { Min = new SerializableVector3I(0, 0, 0), SubtypeName = "LargeWarhead", ColorMaskHSV = new SerializableVector3(0, -1, 0), EntityId = 0, Owner = 0, BlockOrientation = new SerializableBlockOrientation(Base6Directions.Direction.Forward, Base6Directions.Direction.Up), ShareMode = MyOwnershipShareModeEnum.All, CustomName = "Hello. My name is Inigo Montoya. You killed my father. Prepare to die.", }; gridObjectBuilder.CubeBlocks.Add(cube); var tempList = new List<MyObjectBuilder_EntityBase>(); tempList.Add(gridObjectBuilder); tempList.CreateAndSyncEntities(); }
/// <summary> /// Move a player, to another entity (which can be of Grid, Voxel). /// </summary> /// <param name="sourcePlayer"></param> /// <param name="target"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="emptySourceMessage"></param> /// <param name="emptyTargetMessage"></param> /// <param name="noSafeLocationMessage"></param> /// <returns></returns> public static bool MoveTo(IMyPlayer sourcePlayer, IMyEntity target, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { if (sourcePlayer == null) { if (emptySourceMessage != null) emptySourceMessage.Invoke(); return false; } if (target == null || target.Closed) { if (emptyTargetMessage != null) emptyTargetMessage.Invoke(); return false; } if (sourcePlayer.Controller.ControlledEntity is IMyCubeBlock) { // player is piloting a ship. Move ship to entity. return MoveTo(sourcePlayer.Controller.ControlledEntity.Entity.GetTopMostParent(), target, safely, updatedPosition, emptySourceMessage, emptyTargetMessage, noSafeLocationMessage); } // Player is free floating, we move the player only. if (target is IMyCubeGrid) { var grid = (Sandbox.Game.Entities.MyCubeGrid)target; // Station or Large ship grids. if (((IMyCubeGrid)target).GridSizeEnum != MyCubeSize.Small) { IMyControllableEntity targetCockpit = null; if (grid.HasMainCockpit()) { // Select the main cockpit. targetCockpit = (IMyControllableEntity)grid.MainCockpit; } else { var cockpits = target.FindWorkingCockpits(); var operationalCockpit = cockpits.FirstOrDefault(c => ((Sandbox.ModAPI.Ingame.IMyCockpit)c).IsShipControlEnabled()); if (operationalCockpit != null) // find a cockpit which is not a passenger seat. targetCockpit = operationalCockpit; else if (cockpits.Length > 0) targetCockpit = cockpits[0]; } if (targetCockpit != null) return MovePlayerToCube(sourcePlayer, (IMyCubeBlock)targetCockpit, safely, updatedPosition, noSafeLocationMessage); } // Small ship grids. Also the fallback if a large ship does not have a cockpit. return MovePlayerToShipGrid(sourcePlayer, (IMyCubeGrid)target, safely, updatedPosition, noSafeLocationMessage); } if (target is IMyVoxelBase) { return MovePlayerToVoxel(sourcePlayer, (IMyVoxelBase)target, safely, updatedPosition, emptySourceMessage, emptyTargetMessage, noSafeLocationMessage); } return false; }
/// <summary> /// Returns the position of player as Vector3 /// </summary> /// <param name="player"></param> /// <returns></returns> public Vector3D Position(IMyPlayer player) => player.GetPosition();
/// <summary> /// Teleports the player to the specified position /// </summary> /// <param name="player"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> public void Teleport(IMyPlayer player, float x, float y, float z) => Teleport(player, new Vector3D(x, y, z));
/// <summary> /// Teleports the player to the target player /// </summary> /// <param name="player"></param> /// <param name="target"></param> public void Teleport(IMyPlayer player, IMyPlayer target) => Teleport(player, Position(target));
/// <summary> /// Teleports the player to the specified position /// </summary> /// <param name="player"></param> /// <param name="destination"></param> public void Teleport(IMyPlayer player, Vector3D destination) => player.Controller.ControlledEntity.Entity.PositionComp.SetPosition(destination);
/// <summary> /// Renames the player to specified name /// <param name="player"></param> /// <param name="name"></param> /// </summary> public void Rename(IMyPlayer player, string name) { // TODO: Implement when possible }
/// <summary> /// Causes the player to die /// </summary> /// <param name="player"></param> public void Kill(IMyPlayer player) => player.Character.Kill();
/// <summary> /// Kicks the player from the server /// </summary> /// <param name="player"></param> /// <param name="reason"></param> public void Kick(IMyPlayer player, string reason = "") => MyMultiplayer.Static.KickClient(player.SteamUserId);
private static bool FindPlayerFreePosition(ref Vector3D position, IMyPlayer player) { return FindEntityFreePosition(ref position, player.Controller.ControlledEntity.Entity, player.Controller.ControlledEntity.Entity.WorldVolume); }
/// <summary> /// Move a player to a location. /// </summary> /// <param name="sourcePlayer"></param> /// <param name="targetLocation"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="noSafeLocationMessage"></param> /// <returns>Will return false if the move operation could not be carried out.</returns> public static bool MoveTo(IMyPlayer sourcePlayer, Vector3D targetLocation, bool safely, Action<Vector3D> updatedPosition, Action noSafeLocationMessage) { if (sourcePlayer == null) return false; if (sourcePlayer.Controller.ControlledEntity is IMyCubeBlock) { // Move the ship the player is piloting. var cubeGrid = (IMyCubeGrid)sourcePlayer.Controller.ControlledEntity.Entity.GetTopMostParent(); var worldOffset = targetLocation - sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); return MoveShipByOffset(cubeGrid, worldOffset, safely, updatedPosition, noSafeLocationMessage); } // Move the player only. if (safely && !FindPlayerFreePosition(ref targetLocation, sourcePlayer)) { if (noSafeLocationMessage != null) noSafeLocationMessage.Invoke(); return false; } var currentPosition = sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); MessageSyncEntity.Process(sourcePlayer.Controller.ControlledEntity.Entity, SyncEntityType.Position, targetLocation); if (updatedPosition != null) updatedPosition.Invoke(currentPosition); return true; }
/// <summary> /// Gets the player's language /// </summary> public CultureInfo Language(IMyPlayer player) => CultureInfo.GetCultureInfo("en"); // TODO: Implement when possible
private void Slay(IMyPlayer player) { if (player.KillPlayer(MyDamageType.Environment)) MyAPIGateway.Utilities.SendMessage(SenderSteamId, "slaying", player.DisplayName); else MyAPIGateway.Utilities.SendMessage(SenderSteamId, "Failed", "Could not slay '{0}'. Player may be dead already.", player.DisplayName); }
/// <summary> /// Runs the specified player command /// </summary> /// <param name="player"></param> /// <param name="command"></param> /// <param name="args"></param> public void Command(IMyPlayer player, string command, params object[] args) { // TODO: Implement when possible }
private void Eject(IMyPlayer player) { if (player.Controller.ControlledEntity.Entity.Parent != null) { MyAPIGateway.Utilities.SendMessage(SenderSteamId, "ejecting", player.DisplayName); // this will find the cockpit the player's character is inside of. var character = player.GetCharacter(); if (character != null) { var baseController = ((IMyEntity)character).Parent as IMyControllableEntity; if (baseController != null) // this will eject the Character from the cockpit. baseController.Use(); } player.Controller.ControlledEntity.Use(); //// Enqueue the command a second time, to make sure the player is ejected from a remote controlled ship and a piloted ship. //_workQueue.Enqueue(delegate () //{ // if (selectedPlayer.Controller.ControlledEntity.Entity.Parent != null) // { // selectedPlayer.Controller.ControlledEntity.Use(); // } //}); // Neither of these do what I expect them to. In fact, I'm not sure what they do. //MyAPIGateway.Players.RemoveControlledEntity(player.Controller.ControlledEntity.Entity); //MyAPIGateway.Players.RemoveControlledEntity(player.Controller.ControlledEntity.Entity.Parent); } else { MyAPIGateway.Utilities.SendMessage(SenderSteamId, "player", "{0} is not a pilot", player.DisplayName); } }
public CultureInfo Language(IMyPlayer player) => CultureInfo.GetCultureInfo("en"); // TODO: Implement when possible /// <summary> /// Gets the player's IP address /// </summary> public string Address(IMyPlayer player) => "0"; // TODO: Implement when possible
//this method will look for active ship grids/drones/players and keep killing them untill it cant find any within //its local known nearby objects public bool FindNearbyAttackTarget() { //return false; FindWeapons(); ClearTarget(); Dictionary<IMyEntity, IMyEntity> nearbyDrones = new Dictionary<IMyEntity, IMyEntity>(); Dictionary<IMyEntity, IMyEntity> nearbyOnlineShips = new Dictionary<IMyEntity, IMyEntity>(); List<IMyPlayer> nearbyPlayers = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(nearbyPlayers); nearbyPlayers = nearbyPlayers.Where( x => x.PlayerID != _ownerId && (x.GetPosition() - Ship.GetPosition()).Length() < 2000) .ToList(); bool playersNearby = nearbyPlayers.Any(); Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] enemy players nearby? " + playersNearby); for (int i = 0; i < _nearbyFloatingObjects.Count; i++) { if ((_nearbyFloatingObjects.ToList()[i].GetPosition() - Ship.GetPosition()).Length() > 10) { var entity = _nearbyFloatingObjects.ToList()[i]; var grid = entity as IMyCubeGrid; if (grid != null) { var gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid); List<IMyTerminalBlock> val = new List<IMyTerminalBlock>(); gridTerminal.GetBlocks(val); var isFriendly = GridFriendly(val); List<IMyTerminalBlock> T = new List<IMyTerminalBlock>(); gridTerminal.GetBlocksOfType<IMyRemoteControl>(T); List<IMyTerminalBlock> reactorBlocks = new List<IMyTerminalBlock>(); gridTerminal.GetBlocksOfType<IMyPowerProducer>(reactorBlocks); bool isOnline = reactorBlocks.Exists(x => (((IMyPowerProducer)x).CurrentPowerOutput > 0 && x.IsWorking) && !isFriendly); bool isDrone = T.Exists( x => (((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking && !isFriendly)); bool isMothership = T.Exists(x => x.CustomName.Contains("#ConquestMothership")); var droneControl = (IMyEntity) T.FirstOrDefault( x => ((IMyRemoteControl)x).CustomName.Contains("Drone#") && x.IsWorking && !isFriendly); var shipPower = (IMyEntity) reactorBlocks.FirstOrDefault( x => (((IMyPowerProducer)x).CurrentPowerOutput > 0 && x.IsWorking) && !isFriendly); if (isDrone && isOnline) { nearbyDrones.Add(grid, droneControl); } else if (isOnline) { nearbyOnlineShips.Add(grid, shipPower ?? droneControl); } } } } if (nearbyDrones.Count > 0) { Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby drone count " + nearbyDrones.Count); var myTarget = nearbyDrones .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length()) .ToList(); if (myTarget.Count > 0) { var target = myTarget[0]; IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key); List<IMyTerminalBlock> T = new List<IMyTerminalBlock>(); gridTerminal.GetBlocks(T); if (T.Count >= _minTargetSize) { _target = (IMyCubeGrid)target.Key; _targetPlayer = null; try { if (!FindTargetKeyPoint(_target, _target.Physics.LinearVelocity)) OrbitAttackTarget(_target.GetPosition(), _target.Physics.LinearVelocity); return true; } catch { } } } } if (nearbyOnlineShips.Count > 0) { Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby ship count " + nearbyOnlineShips.Count); var myTargets = nearbyOnlineShips .OrderBy(x => (x.Key.GetPosition() - Ship.GetPosition()).Length()) .ToList(); foreach (var target in myTargets) { IMyGridTerminalSystem gridTerminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)target.Key); List<IMyTerminalBlock> T = new List<IMyTerminalBlock>(); gridTerminal.GetBlocks(T); if (T.Count >= _minTargetSize) { _target = (IMyCubeGrid)target.Key; _targetPlayer = null; try { FindTargetKeyPoint(_target, _target.Physics.LinearVelocity); return true; } catch { OrbitAttackTarget(_target.GetPosition(), _target.Physics.LinearVelocity); } } } } //if (playersNearby && nearbyPlayers.Count > 0) //{ // Util.GetInstance().Log("[Drone.FindNearbyAttacktarget] nearby player count " + nearbyPlayers.Count); // var myTarget = nearbyPlayers.OrderBy(x => ((x).GetPosition() - Ship.GetPosition()).Length()).ToList(); // if (myTarget.Count > 0) // { // _target = null; // _targetPlayer = myTarget[0]; // OrbitAttackTarget(_targetPlayer.GetPosition(), new Vector3D(0, 0, 0)); // return true; // } //} return false; }
/// <summary> /// Sends a chat message to the player /// </summary> /// <param name="player"></param> /// <param name="message"></param> /// <param name="prefix"></param> public void Reply(IMyPlayer player, string message, string prefix = null) => Message(player, message, prefix);
public static void SendChatMessage(IMyPlayer receiver, string message) { SendChatMessage(receiver.SteamUserId, message); }
/// <summary> /// Sends a chat message to the player /// </summary> /// <param name="player"></param> /// <param name="message"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Reply(IMyPlayer player, string message, string prefix = null, params object[] args) => Reply(player, string.Format(message, args), prefix);
public static bool IsFullOwner( MyObjectBuilder_CubeGrid grid, long ownerId, IMyPlayer factionPlayer = null ) { bool found = false; foreach ( MyObjectBuilder_CubeBlock block in grid.CubeBlocks ) { if ( !( block is MyObjectBuilder_TerminalBlock ) ) continue; MyObjectBuilder_TerminalBlock functional = (MyObjectBuilder_TerminalBlock)block; if ( factionPlayer == null ) { if ( functional.Owner != 0 && functional.Owner != ownerId ) { return false; } else if ( functional.Owner != 0 ) { found = true; } } else { MyRelationsBetweenPlayerAndBlock relation = factionPlayer.GetRelationTo( functional.Owner ); if ( functional.Owner != 0 && ( relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare ) ) { found = true; } else if ( functional.Owner != 0 && relation != MyRelationsBetweenPlayerAndBlock.FactionShare && relation != MyRelationsBetweenPlayerAndBlock.FactionShare ) { return false; } } } return found; }
public string Address(IMyPlayer player) => "0"; // TODO: Implement when possible /// <summary> /// Gets the player's average network ping /// </summary> public int Ping(IMyPlayer player) => 0; // TODO: Implement when possible
void SendFactionMessage(IMyPlayer receiver, string message) { var privateMessage = new MessageFactionMessage(); privateMessage.ChatMessage = new ChatMessage() { Sender = new Player() { SteamId = MyAPIGateway.Session.Player.SteamUserId, PlayerName = MyAPIGateway.Session.Player.DisplayName }, Text = message, Date = DateTime.Now }; privateMessage.Receiver = receiver.SteamUserId; ConnectionHelper.SendMessageToServer(privateMessage); }
/// <summary> /// Returns if the player is admin /// </summary> public bool IsAdmin(IMyPlayer player) => player.PromoteLevel == MyPromoteLevel.Admin;
/// <summary> /// Move player to Voxel. Either Asteroid or planet. /// </summary> /// <param name="sourcePlayer"></param> /// <param name="targetVoxel"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="emptySourceMessage"></param> /// <param name="emptyTargetMessage"></param> /// <param name="noSafeLocationMessage"></param> /// <returns></returns> public static bool MovePlayerToVoxel(IMyPlayer sourcePlayer, IMyVoxelBase targetVoxel, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { if (sourcePlayer == null) { if (emptySourceMessage != null) emptySourceMessage.Invoke(); return false; } if (targetVoxel == null || targetVoxel.Closed) { if (emptyTargetMessage != null) emptyTargetMessage.Invoke(); return false; } Vector3D position; MatrixD matrix; if (targetVoxel is IMyVoxelMap) { var asteroid = (IMyVoxelMap)targetVoxel; position = asteroid.PositionLeftBottomCorner; // have the player facing the asteroid. var fwd = asteroid.WorldMatrix.Translation - asteroid.PositionLeftBottomCorner; fwd.Normalize(); // calculate matrix to orient player to asteroid center. var up = Vector3D.CalculatePerpendicularVector(fwd); matrix = MatrixD.CreateWorld(position, fwd, up); } else if (targetVoxel is Sandbox.Game.Entities.MyPlanet) { var planet = (Sandbox.Game.Entities.MyPlanet)targetVoxel; // User current player position as starting point to find surface point. Vector3D findFromPoint = sourcePlayer.GetPosition(); Vector3D closestSurfacePoint; MyVoxelCoordSystems.WorldPositionToLocalPosition(planet.PositionLeftBottomCorner, ref findFromPoint, out closestSurfacePoint); position = planet.GetClosestSurfacePointGlobal(ref closestSurfacePoint); var up = position - planet.WorldMatrix.Translation; up.Normalize(); position = position + (up * 0.5d); // add a small margin because the voxel LOD can sometimes push a player down when first loading a distant cluster. // calculate matrix to orient player to planet. var fwd = Vector3D.CalculatePerpendicularVector(up); matrix = MatrixD.CreateWorld(position, fwd, up); } else { return false; } if (safely && !FindPlayerFreePosition(ref position, sourcePlayer)) { if (noSafeLocationMessage != null) noSafeLocationMessage.Invoke(); return false; } var currentPosition = sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); MessageSyncEntity.Process(sourcePlayer.Controller.ControlledEntity.Entity, SyncEntityType.Position | SyncEntityType.Matrix, Vector3.Zero, position, matrix); if (updatedPosition != null) updatedPosition.Invoke(currentPosition); return true; }
/// <summary> /// Gets if the player is banned /// </summary> public bool IsBanned(IMyPlayer player) => IsBanned(player.SteamUserId);
public static bool FindEntitiesNamed(string entityName, bool findPlayers, bool findShips, bool findAsteroids, bool findPlanets, bool findGps, out IMyPlayer player, out IMyEntity entity, out IMyGps gps) { #region Find Exact name match first. var playerList = new List<IMyPlayer>(); var shipList = new HashSet<IMyEntity>(); var asteroidList = new List<IMyVoxelBase>(); var planetList = new List<IMyVoxelBase>(); var gpsList = new List<IMyGps>(); if (findPlayers) MyAPIGateway.Players.GetPlayers(playerList, p => entityName == null || p.DisplayName.Equals(entityName, StringComparison.InvariantCultureIgnoreCase)); if (findShips) shipList = FindShipsByName(entityName); if (findAsteroids) MyAPIGateway.Session.VoxelMaps.GetInstances(asteroidList, v => v is IMyVoxelMap && (entityName == null || v.StorageName.Equals(entityName, StringComparison.InvariantCultureIgnoreCase))); if (findPlanets) MyAPIGateway.Session.VoxelMaps.GetInstances(planetList, v => v is Sandbox.Game.Entities.MyPlanet && (entityName == null || v.StorageName.Equals(entityName, StringComparison.InvariantCultureIgnoreCase))); if (findGps) gpsList = MyAPIGateway.Session.GPS.GetGpsList(MyAPIGateway.Session.Player.IdentityId).Where(g => entityName == null || g.Name.Equals(entityName, StringComparison.InvariantCultureIgnoreCase)).ToList(); // identify a unique ship or player by the name. if (playerList.Count > 1 || shipList.Count > 1 || asteroidList.Count > 1 || planetList.Count > 1 || gpsList.Count > 1) { // TODO: too many entities. hotlist or sublist? string msg = "Too many entries with that name."; if (findPlayers) msg += string.Format(" Players: {0}", playerList.Count); if (findShips) msg += string.Format(" Ships: {0}", shipList.Count); if (findAsteroids) msg += string.Format(" Asteroids: {0}", asteroidList.Count); if (findPlayers) msg += string.Format(" Planets: {0}", planetList.Count); if (findGps) msg += string.Format(" Gps: {0}", gpsList.Count); MyAPIGateway.Utilities.ShowMessage("Cannot match", msg); player = null; entity = null; gps = null; return false; } if (playerList.Count == 1 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 0) { player = playerList[0]; entity = null; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 1 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 0) { player = null; entity = shipList.FirstElement(); gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 1 && planetList.Count == 0 && gpsList.Count == 0) { player = null; entity = asteroidList[0]; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 1 && gpsList.Count == 0) { player = null; entity = planetList[0]; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 1) { player = null; entity = null; gps = gpsList[0]; return true; } #endregion #region find partial name matches. playerList.Clear(); shipList.Clear(); asteroidList.Clear(); planetList.Clear(); gpsList.Clear(); if (findPlayers) MyAPIGateway.Players.GetPlayers(playerList, p => entityName == null || p.DisplayName.IndexOf(entityName, StringComparison.InvariantCultureIgnoreCase) >= 0); if (findShips) shipList = FindShipsByName(entityName, true, false); if (findAsteroids) MyAPIGateway.Session.VoxelMaps.GetInstances(asteroidList, v => v is IMyVoxelMap && (entityName == null || v.StorageName.IndexOf(entityName, StringComparison.InvariantCultureIgnoreCase) >= 0)); if (findPlanets) MyAPIGateway.Session.VoxelMaps.GetInstances(planetList, v => v is Sandbox.Game.Entities.MyPlanet && (entityName == null || v.StorageName.IndexOf(entityName, StringComparison.InvariantCultureIgnoreCase) >= 0)); if (findGps) gpsList = MyAPIGateway.Session.GPS.GetGpsList(MyAPIGateway.Session.Player.IdentityId).Where(g => entityName == null || g.Name.IndexOf(entityName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList(); // identify a unique ship or player by the name. if (playerList.Count > 1 || shipList.Count > 1 || asteroidList.Count > 1 || planetList.Count > 1 || gpsList.Count > 1) { // TODO: too many entities. hotlist or sublist? string msg = "Too many entries with that name."; if (findPlayers) msg += string.Format(" Players: {0}", playerList.Count); if (findShips) msg += string.Format(" Ships: {0}", shipList.Count); if (findAsteroids) msg += string.Format(" Asteroids: {0}", asteroidList.Count); if (findPlayers) msg += string.Format(" Planets: {0}", planetList.Count); if (findGps) msg += string.Format(" Gps: {0}", gpsList.Count); MyAPIGateway.Utilities.ShowMessage("Cannot match", msg); player = null; entity = null; gps = null; return false; } if (playerList.Count == 1 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 0) { player = playerList[0]; entity = null; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 1 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 0) { player = null; entity = shipList.FirstElement(); gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 1 && planetList.Count == 0 && gpsList.Count == 0) { player = null; entity = asteroidList[0]; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 1 && gpsList.Count == 0) { player = null; entity = planetList[0]; gps = null; return true; } if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 1) { player = null; entity = null; gps = gpsList[0]; return true; } #endregion // In reality, this is equivilant to: // if (playerList.Count == 0 && shipList.Count == 0 && asteroidList.Count == 0 && planetList.Count == 0 && gpsList.Count == 0) MyAPIGateway.Utilities.ShowMessage("Error", "Could not find specified object"); player = null; entity = null; gps = null; return false; }
/// <summary> /// Gets if the player is connected /// </summary> public bool IsConnected(IMyPlayer player) => Sync.Clients.HasClient(player.SteamUserId);
/// <summary> /// Move an entity (only Grids can be moved), to a player. /// </summary> /// <param name="source"></param> /// <param name="targetPlayer"></param> /// <param name="safely"></param> /// <param name="updatedPosition"></param> /// <param name="emptySourceMessage"></param> /// <param name="emptyTargetMessage"></param> /// <param name="noSafeLocationMessage"></param> /// <returns>Will return false if the move operation could not be carried out.</returns> public static bool MoveTo(IMyEntity source, IMyPlayer targetPlayer, bool safely, Action<Vector3D> updatedPosition, Action emptySourceMessage, Action emptyTargetMessage, Action noSafeLocationMessage) { if (source == null || source.Closed) { if (emptySourceMessage != null) emptySourceMessage.Invoke(); return false; } if (targetPlayer == null) { if (emptyTargetMessage != null) emptyTargetMessage.Invoke(); return false; } // TODO: Is there a better way of targeting the placement of a ship near a player? return MoveTo(source, targetPlayer.GetPosition(), safely, updatedPosition, emptySourceMessage, noSafeLocationMessage); }
public bool IsSleeping(ulong id) => false; // TODO: Implement if possible /// <summary> /// Returns if the player is sleeping /// </summary> public bool IsSleeping(IMyPlayer player) => IsSleeping(player.SteamUserId);
public RequestParamParser(IMyPlayer player, IEnumerable <string> arguments) { var args = new Dictionary <string, string>(); foreach (var argument in arguments) { if (!argument.StartsWith("--")) { continue; } var arg = argument.Substring(2, argument.Length - 2); var keyValuePair = arg.Split('='); var key = keyValuePair[0]; var value = keyValuePair.Length >= 2 ? keyValuePair[1] : ""; // empty string if parameter-less args[key] = value; } if (args.TryGetValue("secs", out var tickStr)) { if (!uint.TryParse(tickStr, out var tick)) { throw new Exception($"Failed to parse tick: '{tickStr}'"); } Seconds = tick; } if (args.TryGetValue("top", out var topStr)) { if (!int.TryParse(topStr, out var topInput)) { throw new Exception($"Failed to parse top: '{topStr}'"); } Top = topInput; } if (args.TryGetValue("gps", out _)) { if (player == null) { throw new Exception("GPS return can only be used by players"); } SendGpsToPlayer = true; PlayerIdToSendGps = player.IdentityId; } if (args.TryGetValue("details", out _) || args.TryGetValue("detail", out _)) { ShowDetails = true; } if (args.TryGetValue("faction", out var factionName)) { if (!ResolveFaction(factionName, out var id)) { throw new Exception($"Failed to find faction {factionName}"); } FactionMask = id?.FactionId ?? 0; } if (args.TryGetValue("player", out var playerName)) { if (!ResolveIdentity(playerName, out var id)) { throw new Exception($"Failed to find player {playerName}"); } PlayerMask = id?.IdentityId ?? 0; } if (args.TryGetValue("entity", out var entityIdStr)) { if (!long.TryParse(entityIdStr, out var entityId)) { throw new Exception($"Failed to parse grid ID={entityIdStr}"); } if (!(MyEntities.GetEntityById(entityId) is MyCubeGrid)) { throw new Exception($"Failed to find grid with ID={entityId}"); } GridMask = entityId; } if (args.TryGetValue("this", out _)) { var controlled = player?.Controller?.ControlledEntity?.Entity; if (controlled == null) { throw new Exception("You must have a controlled entity to use the --this argument"); } MyCubeGrid grid; var tmp = controlled; do { grid = tmp as MyCubeGrid; if (grid != null) { break; } tmp = tmp.Parent; } while (tmp != null); if (grid == null) { throw new Exception("You must be controlling a grid to use the --this argument"); } GridMask = grid.EntityId; } }
public static bool HasPermission(this IMyPlayer player, Vector3D location, MyStringId id) { return(MyAreaPermissionSystem.Static == null || MyAreaPermissionSystem.Static.HasPermission(player.IdentityId, location, id)); }
private void Slap(IMyPlayer player) { var character = player.GetCharacter(); var destroyable = character as IMyDestroyableObject; if (destroyable == null) { MyAPIGateway.Utilities.SendMessage(SenderSteamId, "Failed", "Could not slap '{0}'. Player may be dead.", player.DisplayName); return; } MyAPIGateway.Utilities.SendMessage(SenderSteamId, "slapping", player.DisplayName); MyAPIGateway.Utilities.SendMessage(player.SteamUserId, "Server", "You were slapped"); if (destroyable.Integrity > 1f) destroyable.DoDamage(1f, MyDamageType.Environment, true); // TODO: does not work on the server. Will need to be implmented on Client. //var physics = ((IMyEntity)character).Physics; //if (physics != null) //{ // Vector3 random = new Vector3(); // random.X = 2.0f * (float)_random.NextDouble() - 1.0f; // random.Y = 2.0f * (float)_random.NextDouble() - 1.0f; // random.Z = 2.0f * (float)_random.NextDouble() - 1.0f; // random.Normalize(); // physics.ApplyImpulse(random * 500, Vector3.Zero); // 5m/s. //} }
public static bool IsCreative(this IMyPlayer player) { return(MyAPIGateway.Session.CreativeMode || MyAPIGateway.Session.IsAdminModeEnabled(player.IdentityId)); }
private void ThrowMeteor(IMyPlayer player, string oreName) { MatrixD worldMatrix; Vector3D position; if (player.Controller.ControlledEntity.Entity.Parent == null) { worldMatrix = player.Controller.ControlledEntity.GetHeadMatrix(true, true, false); // dead center of player cross hairs. position = worldMatrix.Translation + worldMatrix.Forward * 1.5f; // Spawn item 1.5m in front of player for safety. } else { worldMatrix = player.Controller.ControlledEntity.Entity.WorldMatrix; position = worldMatrix.Translation + worldMatrix.Forward * 1.5f + worldMatrix.Up * 0.5f; // Spawn item 1.5m in front of player in cockpit for safety. } var meteorBuilder = new MyObjectBuilder_Meteor() { Item = new MyObjectBuilder_InventoryItem() { Amount = 10000, Content = new MyObjectBuilder_Ore() { SubtypeName = oreName } }, PersistentFlags = MyPersistentEntityFlags2.InScene, // Very important PositionAndOrientation = new MyPositionAndOrientation() { Position = position, Forward = (Vector3)worldMatrix.Forward, Up = (Vector3)worldMatrix.Up, }, LinearVelocity = worldMatrix.Forward * 500, Integrity = 100, }; meteorBuilder.CreateAndSyncEntity(); }
public override bool Invoke(ulong steamId, long playerId, string messageText) { var match = Regex.Match(messageText, @"/eject\s+(?:(?:""(?<name>[^""]|.*?)"")|(?<name>.*))", RegexOptions.IgnoreCase); if (match.Success) { var playerName = match.Groups["name"].Value; var players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players, p => p != null); IMyPlayer selectedPlayer = null; var findPlayer = players.FirstOrDefault(p => p.DisplayName.Equals(playerName, StringComparison.InvariantCultureIgnoreCase)); if (findPlayer != null) { selectedPlayer = findPlayer; } int index; List <IMyIdentity> cacheList = CommandPlayerStatus.GetIdentityCache(steamId); if (playerName.Substring(0, 1) == "#" && int.TryParse(playerName.Substring(1), out index) && index > 0 && index <= cacheList.Count) { var listplayers = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(listplayers, p => p.PlayerID == cacheList[index - 1].PlayerId); selectedPlayer = listplayers.FirstOrDefault(); } if (selectedPlayer == null) { MyAPIGateway.Utilities.SendMessage(steamId, "Eject", "No player named '{0}' found.", playerName); return(true); } MessageSyncAres.Eject(selectedPlayer.SteamUserId); return(true); // NPC's do not appears as Players, but Identities. // There could be multiple Identities with the same name, for active, inactive and dead. //if (playerName.Substring(0, 1) == "B" && Int32.TryParse(playerName.Substring(1), out index) && index > 0 && index <= CommandListBots.BotCache.Count) //{ // selectedPlayer = CommandListBots.BotCache[index - 1]; //} // TODO: figure out how to eject Autopilot. //var entities = new HashSet<IMyEntity>(); //MyAPIGateway.Entities.GetEntities(entities, e => e is IMyCubeGrid); //foreach (var entity in entities) //{ // var cockpits = entity.FindWorkingCockpits(); // foreach (var cockpit in cockpits) // { // var block = (IMyCubeBlock)cockpit; // if (block.OwnerId == selectedPlayer.PlayerId) // { // MyAPIGateway.Utilities.SendMessage(steamId, "ejecting", selectedPlayer.DisplayName); // // Does not appear to eject Autopilot. // cockpit.Use(); // } // } //} } return(false); }
/// <summary> /// Any player who owns a block on the grid can modify it. If noone owns a block everyone can modify it. /// </summary> /// <param name="player"></param> /// <param name="block"></param> /// <returns></returns> public static bool CanModify(IMyPlayer player, IMySlimBlock block) { return CanModify(player, block.CubeGrid); }
public static bool TryGetPlayer(this IMyPlayerCollection collection, string name, out IMyPlayer player) { player = null; if (string.IsNullOrEmpty(name)) { return(false); } var players = new List <IMyPlayer>(); collection.GetPlayers(players, p => p != null); player = players.FirstOrDefault(p => p.DisplayName.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (player == null) { return(false); } return(true); }
void SendPrivateMessage(IMyPlayer receiver, string message) { if (string.IsNullOrEmpty(message)) MyAPIGateway.Utilities.ShowMessage("PM System", "Message too short."); var privateMessage = new MessagePrivateMessage(); privateMessage.ChatMessage = new ChatMessage() { Sender = new Player() { SteamId = MyAPIGateway.Session.Player.SteamUserId, PlayerName = MyAPIGateway.Session.Player.DisplayName }, Text = message, Date = DateTime.Now }; privateMessage.Receiver = receiver.SteamUserId; ConnectionHelper.SendMessageToServer(privateMessage); MyAPIGateway.Utilities.ShowMessage(string.Format("Whispered {0}", receiver.DisplayName), message); }
public static bool TryGetPlayer(this IMyPlayerCollection collection, ulong steamId, out IMyPlayer player) { player = null; if (steamId == 0) { return(false); } var players = new List <IMyPlayer>(); collection.GetPlayers(players, p => p != null); player = players.FirstOrDefault(p => p.SteamUserId == steamId); if (player == null) { return(false); } return(true); }
//sets targets to null private void ClearTarget() { _target = null; _targetPlayer = null; }
public override bool HandleCommand(ulong userId, string[] words) { if (false) { /* * HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); * MyAPIGateway.Entities.GetEntities(entities); * IMyEntity target = null; * bool skip = true; * foreach (IMyEntity entity in entities) * { * if (!(entity is IMyVoxelMap)) * continue; * * if (!entity.Save) * continue; * * if (skip) * { * skip = false; * continue; * } * * target = entity; * break; * } * * if (target == null) * return true; * * DateTime start = DateTime.Now; * IMyVoxelMap voxel = (IMyVoxelMap)target; * * Console.WriteLine(string.Format("Here: {0}", voxel.StorageName)); * * MyStorageDataCache cache = new MyStorageDataCache(); * Vector3I size = voxel.Storage.Size; * cache.Resize(size); * Vector3I chunkSize = new Vector3I(32, 32, 32); * //voxel.Storage.ReadRange(cache, MyStorageDataTypeFlags.All, 0, Vector3I.Zero, voxel.Storage.Size - 1); * MyStorageDataCache[] cacheParts = new MyStorageDataCache[32 * 32 * 32]; * * Parallel.For(0, size.X / chunkSize.X, x => * { * Parallel.For(0, size.Y / chunkSize.Y, y => * { * Parallel.For(0, size.Z / chunkSize.Z, z => * { * cacheParts[x * y * z] = new MyStorageDataCache(); * MyStorageDataCache localCache = cacheParts[x * y * z]; * localCache.Resize(new Vector3I(32, 32, 32)); * //Console.WriteLine("Read: {0} - {1} - {2}", x, y, z); * Vector3I cstart = new Vector3I(32 * x, 32 * y, 32 * z); * Vector3I cend = new Vector3I(32 * (x + 1), 32 * (y + 1), 32 * (z + 1)); * voxel.Storage.ReadRange(localCache, MyStorageDataTypeFlags.ContentAndMaterial, 0, cstart, cend - 1); * //Console.WriteLine("Done Read: {0} - {1} - {2}", x, y, z); * }); * }); * }); * * MyObjectBuilder_VoxelMap voxelBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_VoxelMap>(); * voxelBuilder.StorageName = "testRoid"; * voxelBuilder.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene; * voxelBuilder.PositionAndOrientation = new MyPositionAndOrientation?(MyPositionAndOrientation.Default); * voxelBuilder.MutableStorage = false; * * IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(voxelBuilder); * if (newEntity != null) * { * Console.WriteLine("Added"); * } * * Parallel.For(0, size.X / chunkSize.X, x => * { * Parallel.For(0, size.Y / chunkSize.Y, y => * { * Parallel.For(0, size.Z / chunkSize.Z, z => * { * }); * }); * }); * * // IMyVoxelMap myVoxelMap = new IMyVoxelMap(); * // { * // EntityId = 0; * // }; * //myVoxelMap.Init(str, myStorageBase, asteroidDetails.Position - (myStorageBase.Size * 0.5f)); * // myVoxelMap.Init(voxelBuilder); * * //for(int x = 0; x < size.X / 32; x++) * //{ * //} * * Console.WriteLine(string.Format("Cache read in {0} ms", (DateTime.Now - start).TotalMilliseconds)); * * //MyObjectBuilder_VoxelMap voxel = * */ //ServerNetworkManager.ShowRespawnMenu(userId); } /* * CubeGridEntity entity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "Platform.sbc")); * //IMyEntity entity = new IMyEntities(new FileInfo(Essentials.PluginPath + "Platform.sbc")); * long entityId = BaseEntity.GenerateEntityId(); * entity.EntityId = entityId; * entity.PositionAndOrientation = new MyPositionAndOrientation((new Vector3(0,0,0)), Vector3.Forward, Vector3.Up); * SectorObjectManager.Instance.AddEntity(entity); * //TimedEntityCleanup.Instance.Add( entityId ); * * //MyAPIGateway.Entities.AddEntity (entity, true); * //IMyPlayer.AddGrid(entityId); */ Vector3D position = Vector3D.Zero; Wrapper.GameAction(() => { List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players, x => x.SteamUserId == userId); if (players.Count > 0) { IMyPlayer player = players.First(); position = player.GetPosition(); } }); //return position; Communication.SendPrivateInformation(userId, string.Format("Position - X:{0:F2} Y:{1:F2} Z:{2:F2}", position.X, position.Y, position.Z)); return(true); }
public override bool Invoke(string messageText) { if (!MyAPIGateway.Multiplayer.MultiplayerActive) { MyAPIGateway.Utilities.ShowMessage("PM System", "Command disabled in offline mode."); return true; } //TODO: matching playernames var match = Regex.Match(messageText, @"@@@@@\s+(?<Key>.+)", RegexOptions.IgnoreCase); if (match.Success) { string message = match.Groups["Key"].Value; IMyPlayer lastWhisper = null; if (MyAPIGateway.Players.TryGetPlayer(LastWhisperId, out lastWhisper)) { SendPrivateMessage(lastWhisper, message); return true; } MyAPIGateway.Utilities.ShowMessage("PM System", "Could not find player. Either no one whispered to you or he is offline now."); return true; } var match1 = Regex.Match(messageText, @"@@@@(\s+(?<Key>.+)|)", RegexOptions.IgnoreCase); if (match1.Success) { string message = match1.Groups["Key"].Value; IMyPlayer lastWhisper = null; if (MyAPIGateway.Players.TryGetPlayer(LastWhisperId, out lastWhisper)) { if (!string.IsNullOrEmpty(message)) SendPrivateMessage(lastWhisper, message); WhisperPartner = lastWhisper; MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Set whisperpartner to {0}", WhisperPartner.DisplayName)); return true; } MyAPIGateway.Utilities.ShowMessage("PM System", "Could not find player. Either no one whispered to you or he is offline now."); return true; } var match2 = Regex.Match(messageText, @"@@@\s+((?<Player>[^\s]+)\s+(?<Message>.*)|(?<Player>.+))", RegexOptions.IgnoreCase); if (match2.Success) { var playerName = match2.Groups["Player"].Value; var message = match2.Groups["Message"].Value; IMyPlayer receiver; int index; if (MyAPIGateway.Players.TryGetPlayer(playerName, out receiver)) { if (!string.IsNullOrEmpty(message)) SendPrivateMessage(receiver, message); WhisperPartner = receiver; MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Set whisperpartner to {0}", WhisperPartner.DisplayName)); } else if (playerName.Substring(0, 1) == "#" && Int32.TryParse(playerName.Substring(1), out index) && index > 0 && index <= CommandPlayerStatus.IdentityCache.Count) { var listplayers = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(listplayers, p => p.PlayerID == CommandPlayerStatus.IdentityCache[index - 1].PlayerId); receiver = listplayers.FirstOrDefault(); if (!string.IsNullOrEmpty(message)) SendPrivateMessage(receiver, message); WhisperPartner = receiver; MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Set whisperpartner to {0}", WhisperPartner.DisplayName)); } else MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Player {0} does not exist.", match2.Groups["KeyPlayer"].Value)); return true; } var match3 = Regex.Match(messageText, @"@@\s+(?<Key>.+)", RegexOptions.IgnoreCase); if (match3.Success) { if (WhisperPartner == null) { MyAPIGateway.Utilities.ShowMessage("PM System", "No whisperpartner set"); return true; } //make sure player is online if (MyAPIGateway.Players.TryGetPlayer(WhisperPartner.SteamUserId, out WhisperPartner)) { SendPrivateMessage(WhisperPartner, match3.Groups["Key"].Value); return true; } MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Player {0} is offline.", WhisperPartner.DisplayName)); return true; } var match4 = Regex.Match(messageText, @"(@|/msg|/tell)\s+(?<Player>[^\s]+)\s+(?<Message>.+)", RegexOptions.IgnoreCase); if (match4.Success) { var playerName = match4.Groups["Player"].Value; IMyPlayer receiver; int index; if (MyAPIGateway.Players.TryGetPlayer(playerName, out receiver)) SendPrivateMessage(receiver, match4.Groups["Message"].Value); else if (playerName.Substring(0, 1) == "#" && Int32.TryParse(playerName.Substring(1), out index) && index > 0 && index <= CommandPlayerStatus.IdentityCache.Count) { var listplayers = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(listplayers, p => p.PlayerID == CommandPlayerStatus.IdentityCache[index - 1].PlayerId); receiver = listplayers.FirstOrDefault(); SendPrivateMessage(receiver, match4.Groups["Message"].Value); } else MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Player {0} does not exist.", match4.Groups["KeyPlayer"].Value)); return true; } var match5 = Regex.Match(messageText, @"@\?", RegexOptions.IgnoreCase); if (match5.Success) { if (WhisperPartner != null) MyAPIGateway.Utilities.ShowMessage("PM System", string.Format("Your current whisperpartner is {0}.", WhisperPartner.DisplayName)); else MyAPIGateway.Utilities.ShowMessage("PM System", "No whisperpartner set."); return true; } return false; }
public static bool IsHost(this IMyPlayer player) { return(Sandbox.ModAPI.MyAPIGateway.Multiplayer.IsServerPlayer(player.Client)); }
public static bool isDev(IMyPlayer player) { return isDev(player.SteamUserId); }
public static void SetO2Level(this IMyPlayer player, float level) { actionSetO2LevelForPlayer.CallToServer(player.IdentityId, level); }
public static void OnPlayerLeave(IMyPlayer player) { if (User.Remove(player.PlayerID)) staticLogger.debugLog("removed settings for: " + player.DisplayName + '(' + player.PlayerID + ')', "OnPlayerLeave()"); }
public static float GetO2Level(this IMyPlayer player) { return(MyVisualScriptLogicProvider.GetPlayersOxygenLevel(player.IdentityId)); }
private void RegisterForUpdates(uint frequency, Action toInvoke, IMyPlayer unregisterOnLeaving, Action<IMyPlayer> onLeaving = null) { UpdateList(frequency).Add(toInvoke); PlayerLeaves.Add(unregisterOnLeaving, () => { UnRegisterForUpdates(frequency, toInvoke); try { if (onLeaving != null) onLeaving.Invoke(unregisterOnLeaving); } catch (Exception ex) { myLogger.debugLog("Exception in onLeaving: " + ex, Logger.severity.ERROR); Logger.debugNotify("Exception on player leaving", 10000, Logger.severity.ERROR); } }); }
/// <summary> /// Finds the closest player owned market of the specified open state. /// </summary> /// <returns></returns> public static MarketStruct FindClosestPlayerMarket(IMyPlayer player, bool?isOpen = null) { var character = player.Character; if (character == null) { // Cannot determine the player's location. return(null); } var position = character.GetPosition(); var markets = EconomyScript.Instance.Data.Markets.Where(m => m.MarketId == player.SteamUserId && (!isOpen.HasValue || m.Open == isOpen.Value)).ToArray(); if (markets.Length == 0) { // no open markets found for the player; return(null); } var list = new Dictionary <IMyTerminalBlock, double>(); foreach (var market in markets) { IMyEntity entity; if (!MyAPIGateway.Entities.TryGetEntityById(market.EntityId, out entity)) { continue; } if (entity.Closed || entity.MarkedForClose) { continue; } IMyBeacon beacon = entity as IMyBeacon; if (beacon == null) { continue; } if (beacon.GetUserRelationToOwner(player.IdentityId) != MyRelationsBetweenPlayerAndBlock.Owner) { // Close the market, because it's no longer owner by the player. market.Open = false; continue; } // TODO: should only return markets in the set range. var distance = (position - beacon.WorldMatrix.Translation).Length(); list.Add(beacon, distance); } if (list.Count == 0) { return(null); } var closetEntity = list.OrderBy(f => f.Value).First().Key; var closetMarket = EconomyScript.Instance.Data.Markets.First(m => m.MarketId == player.SteamUserId && (!isOpen.HasValue || m.Open == isOpen.Value) && m.EntityId == closetEntity.EntityId); return(closetMarket); }
void SendToFaction(string message, IMyFaction plFaction, IMyPlayer Me) { var listplayers = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(listplayers); IMyPlayer Receiver; foreach (IMyPlayer pl in listplayers) { if (plFaction.IsMember(pl.PlayerID)) { Receiver = pl; if (Me.DisplayName != Receiver.DisplayName) { if (MyAPIGateway.Players.TryGetPlayer(Receiver.DisplayName, out Receiver)) { SendFactionMessage(Receiver, message); break; } } } } }
public static bool MovePlayerToShipGrid(IMyPlayer sourcePlayer, IMyCubeGrid targetGrid, bool safely, Action<Vector3D> updatedPosition, Action noSafeLocationMessage) { Vector3D destination; if (safely) { // Find empty location, centering on the ship grid. var freePos = MyAPIGateway.Entities.FindFreePlace(targetGrid.WorldAABB.Center, (float)sourcePlayer.Controller.ControlledEntity.Entity.WorldVolume.Radius, 500, 20, 1f); if (!freePos.HasValue) { if (noSafeLocationMessage != null) noSafeLocationMessage.Invoke(); return false; } // Offset will center the player character in the middle of the location. var offset = sourcePlayer.Controller.ControlledEntity.Entity.WorldAABB.Center - sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); destination = freePos.Value - offset; } else { destination = targetGrid.WorldAABB.GetCorners()[0]; } var currentPosition = sourcePlayer.Controller.ControlledEntity.Entity.GetPosition(); MessageSyncEntity.Process(sourcePlayer.Controller.ControlledEntity.Entity, SyncEntityType.Position | SyncEntityType.Velocity, targetGrid.Physics.LinearVelocity, destination); if (updatedPosition != null) updatedPosition.Invoke(currentPosition); return true; }
public static bool IsAdmin(IMyPlayer Player = null, ulong SteamUserId = 0) { // Credits go to Midspace AKA Screaming Angels for this one: // Attempts to determine if a player is an administrator of a dedicated server. var clients = MyAPIGateway.Session.GetCheckpoint("null").Clients; if (clients == null) return false; var client = clients.FirstOrDefault(c => c.SteamId == ((SteamUserId > 0) ? SteamUserId : ((Player != null) ? Player.SteamUserId : 0))); return (client != null && client.IsAdmin); }
/// <summary> /// Heals the player by specified amount /// </summary> /// <param name="player"></param> /// <param name="amount"></param> public void Heal(IMyPlayer player, float amount) => (player as MyPlayer).Character.StatComp.Health.Increase(amount, null);