/// <summary> /// Renders an Entity at a specified X Y position. /// </summary> /// <param name="e">The Entity to render.</param> /// <param name="x">The X position to place the Entity for rendering.</param> /// <param name="y">The Y position to place the Entity for rendering.</param> public static void Entity(Entity e, float x = 0, float y = 0) { var tempX = e.X; var tempY = e.Y; e.SetPosition(x, y); Entity(e); e.SetPosition(tempX, tempY); }
public override void Collide(Entity entity) { base.Enter(entity); if (entity is PlayerEntity) ((PlayerEntity)entity).OnGrounded(); else return; Block block; if (Id % 2 == 0) block = Level.GetBlockById(Id + 1); else block = Level.GetBlockById(Id - 1); entity.SetPosition(block.GetPosition() - new Vector2(0, entity.GetBounds().Height)); float vy = Math.Min(-500, entity.GetVelocity().Y * -.89f); entity.SetVelocity(0, vy); }
private void showResults() { var entities = GameScene.Instance.GetEntities <Entity>(); foreach (Entity obj in entities) { if (obj != this) { obj.RemoveSelf(); } } Label tmp = null; if (_team == Team.Blu) { tmp = new Label(Game.HalfWidth, 200, "YOU LOSE", Color.Red, 0, false, 24); } else { tmp = new Label(Game.HalfWidth, 200, "YOU WIN", Color.Green, 0, false, 24); } GameScene.Instance.Add(new Cursor()); tmp.Graphic.CenterOrigin(); GameScene.Instance.Add(tmp); var statsOffset = Game.HalfWidth + 200; var exit = new Control("ui/buttonMenu.png", Game.HalfWidth - 65, 600); exit.onClick = delegate() { GameScene.Instance.RemoveAll(); ((GameScene)GameScene.Instance).showMenu(); }; GameScene.Instance.Add(exit); var listResults = new List <Label>(); listResults.Add(new Label(statsOffset, 250, "Units produced: " + StatisticWatcher.unitsProduced.ToString(), Color.White)); listResults.Add(new Label(statsOffset, 300, "Units killed: " + StatisticWatcher.unitsKilled.ToString(), Color.White)); listResults.Add(new Label(statsOffset, 350, "Damage done: " + StatisticWatcher.damageDone.ToString(), Color.White)); listResults.Add(new Label(statsOffset, 400, "Coins earned: " + StatisticWatcher.coinsEarned.ToString(), Color.White)); listResults.Add(new Label(statsOffset, 450, "HP healed: " + StatisticWatcher.healthHealed.ToString(), Color.White)); listResults.Add(new Label(statsOffset, 500, "------------------", Color.White)); listResults.Add(new Label(statsOffset, 550, "Total points: " + StatisticWatcher.totalPoints.ToString(), Color.Cyan)); foreach (Label label in listResults) { label.Graphic.CenterOrigin(); GameScene.Instance.Add(label); } using (var stream = new StreamWriter("results.dat", true)) { stream.WriteLine(Environment.UserName + ':' + StatisticWatcher.totalPoints.ToString()); } //statistic grafic here, still WIP float scaleX = (float)425 / (float)StatisticWatcher.statistic.Count; float scaleY = (float)325 / (float)StatisticWatcher.maxPoints; Point graphStart = new Point(50, 565); Console.WriteLine("Scale: {0}; {1}", scaleX, scaleY); var startValue = 0; var field = new Entity(); if (scaleX < 1) { field.Graphic = Image.CreateRectangle(425, 325, Color.Mix(Color.Gray, Color.Black)); scaleX = 1; startValue = StatisticWatcher.lastRecord - 425 * StatisticWatcher.updatePeriod; } else { field.Graphic = Image.CreateRectangle(425, 325, Color.Mix(Color.Gray, Color.Black)); } field.SetPosition(50, 240); GameScene.Instance.Add(field); for (var time = startValue; time <= StatisticWatcher.lastRecord; time += StatisticWatcher.updatePeriod) { var temp = new Entity(); temp.Graphic = Image.CreateRectangle((int)scaleX, (int)((StatisticWatcher.statistic[time]) * scaleY), Color.Cyan); temp.SetPosition(graphStart.X + (float)Math.Round(scaleX, 2) * time / StatisticWatcher.updatePeriod, graphStart.Y - StatisticWatcher.statistic[time] * scaleY); GameScene.Instance.Add(temp); } }
public static void Exec2(ClientInfo _cInfo, Entity _player, int _vehicle) { string _sql = ""; if (_vehicle == 1) { _sql = string.Format("SELECT bikeId FROM Vehicles WHERE steamid = '{0}'", _cInfo.playerId); } if (_vehicle == 2) { _sql = string.Format("SELECT miniBikeId FROM Vehicles WHERE steamid = '{0}'", _cInfo.playerId); } if (_vehicle == 3) { _sql = string.Format("SELECT motorBikeId FROM Vehicles WHERE steamid = '{0}'", _cInfo.playerId); } if (_vehicle == 4) { _sql = string.Format("SELECT jeepId FROM Vehicles WHERE steamid = '{0}'", _cInfo.playerId); } if (_vehicle == 5) { _sql = string.Format("SELECT gyroId FROM Vehicles WHERE steamid = '{0}'", _cInfo.playerId); } DataTable _result = SQL.TQuery(_sql); int _Id; int.TryParse(_result.Rows[0].ItemArray.GetValue(0).ToString(), out _Id); _result.Dispose(); if (_Id != 0) { List <Entity> Entities = GameManager.Instance.World.Entities.list; for (int i = 0; i < Entities.Count; i++) { Entity _entity = Entities[i]; if (!_entity.IsClientControlled()) { if (_entity.entityId == _Id) { if ((_player.position.x - _entity.position.x) * (_player.position.x - _entity.position.x) + (_player.position.z - _entity.position.z) * (_player.position.z - _entity.position.z) <= 50 * 50) { if (_entity.AttachedToEntity == false) { _entity.SetPosition(_player.position); string _phrase782; if (!Phrases.Dict.TryGetValue(782, out _phrase782)) { _phrase782 = " found your vehicle and sent it to you."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase782 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); if (Wallet.IsEnabled && Command_Cost >= 1) { Wallet.SubtractCoinsFromWallet(_cInfo.playerId, Command_Cost); } if (_vehicle == 1) { _sql = string.Format("UPDATE Vehicles SET lastBike = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); } if (_vehicle == 2) { _sql = string.Format("UPDATE Vehicles SET lastMiniBike = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); } if (_vehicle == 3) { _sql = string.Format("UPDATE Vehicles SET lastMotorBike = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); } if (_vehicle == 4) { _sql = string.Format("UPDATE Vehicles SET lastJeep = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); } if (_vehicle == 5) { _sql = string.Format("UPDATE Vehicles SET lastGyro = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); } SQL.FastQuery(_sql, "VehicleTeleport"); return; } else { string _phrase785; if (!Phrases.Dict.TryGetValue(785, out _phrase785)) { _phrase785 = " found your vehicle but someone else is on it."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase785 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); return; } } } } } string _phrase784; if (!Phrases.Dict.TryGetValue(784, out _phrase784)) { _phrase784 = " could not find your vehicle near by."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase784 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } else { string _phrase783; if (!Phrases.Dict.TryGetValue(783, out _phrase783)) { _phrase783 = " you do not have this vehicle type saved."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase783 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } }
/// <summary> /// attempts to move the character to position + deltaMovement. Any colliders in the way will cause the movement to /// stop when run into. /// </summary> /// <param name="deltaMovement">Delta movement.</param> public void Move(Vector3 deltaMovement) { // save off our current grounded state which we will use for becameGroundedThisFrame var oldCollisionState = new CollisionState2D(collision); // clear our state collision.Reset(); _raycastHitsThisFrame.Clear(); _isGoingUpSlope = false; var desiredPosition = entity.Position + deltaMovement; primeRaycastOrigins(desiredPosition, deltaMovement); // first, we check for a slope below us before moving // only check slopes if we are going down and grounded if (deltaMovement.y < 0 && oldCollisionState.Below) { handleVerticalSlope(ref deltaMovement); } // now we check movement in the horizontal dir if (Mathf.Abs(deltaMovement.x) > 0) { moveHorizontally(ref deltaMovement, oldCollisionState); } // next, check movement in the vertical dir if (Mathf.Abs(deltaMovement.y) > 0) { moveVertically(ref deltaMovement, oldCollisionState); } // move then update our state if (data.usePhysicsForMovement) { rigidBody.MovePosition(entity.Position + deltaMovement); velocity = rigidBody.velocity; } else { //transform.Translate( deltaMovement, Space.World ); var newPosition = entity.Position + deltaMovement; entity.SetPosition(newPosition); // only calculate velocity if we have a non-zero deltaTime if (FrameCounter.Instance.deltaTime > 0) { velocity = deltaMovement / FrameCounter.Instance.deltaTime; } } // After translation, update proximity check so collision state is fresh. // Without this, collision state doesn't get updated if there's no delta movement. collision = CheckProximity(data.skinWidth * 2, Direction2D.ALL); // Add to the collision buffer. collisionBuffer.AddFirst(new CollisionState2D(collision)); if (collisionBuffer.Count > data.collisionBufferMax) { collisionBuffer.RemoveLast(); } // set our becameGrounded state based on the previous and current collision state if (!oldCollisionState.Below && collision.Below) { collision.becameGroundedThisFrame = true; } // if we are going up a slope we artificially set a y velocity so we need to zero it out here if (_isGoingUpSlope) { velocity.y = 0; } // send off the collision events if we have a listener if (OnControllerCollidedEvent != null) { for (var i = 0; i < _raycastHitsThisFrame.Count; i++) { OnControllerCollidedEvent(_raycastHitsThisFrame[i]); } } }
public static void Resolve(NetworkMessage.Type messageType, NetDataReader data) { switch (messageType) { case NetworkMessage.Type.server_loginAnswer: { NetworkMessage.LoginType loginAnswer = (NetworkMessage.LoginType)data.GetByte(); if (loginAnswer == NetworkMessage.LoginType.correct) { //Game.GetPlayer().SetPlayerId(data.GetInt()); LoginScreenUI.SetCharacterSelectionWaitingCount(data.GetByte()); return; } LoginScreenUI.ShowInfo(loginAnswer.ToString()); break; } case NetworkMessage.Type.server_characterLoginInfo: { int id = data.GetInt(); string name = data.GetString(data.GetByte()); Vector3 position = new Vector3(data.GetFloat(), data.GetFloat(), data.GetFloat()); float orientation = data.GetFloat(); int modelId = data.GetByte(); int index = Database.GetDBCharacterModelList().FindIndex(x => x.id == modelId); if (index == -1) { Debug.LogError("Cannot find modelId '" + modelId + "'"); index = 0; } Entity ent = Database.CreateEntity(); ent.DisableMovement(true); ent.SetId(id); ent.name = name; ent.SetPostStartAction(() => { GameObject obj = GameObject.Find("SpawnPoint"); ent.transform.SetParent(obj.transform); ent.transform.localPosition = Vector3.zero; ent.SetOrientation(obj.transform.eulerAngles.y); ent.GetVisualModule().AssignCharacterModelToEntity(Database.GetDBCharacterModelList()[index]); LoginScreenUI.AddCharacterSelectionEntity(ent); }); break; } case NetworkMessage.Type.server_requestMapLoading: { //load some map break; } case NetworkMessage.Type.server_createEntity: { int id = data.GetInt(); string name = data.GetString(data.GetByte()); Vector3 position = new Vector3(data.GetFloat(), data.GetFloat(), data.GetFloat()); float orientation = data.GetFloat(); int modelId = data.GetByte(); Vector3 userInput = new Vector3(data.GetFloat(), data.GetFloat(), data.GetFloat()); int index = Database.GetDBCharacterModelList().FindIndex(x => x.id == modelId); if (index == -1) { Debug.LogError("Cannot find modelId '" + modelId + "'"); index = 0; } Entity ent = Database.CreateEntity(); ent.SetId(id); ent.name = name; ent.SetPostStartAction(() => { ent.SetPosition(position); ent.SetOrientation(orientation); ent.GetMovementModule().SetRequestInputs(userInput); ent.GetVisualModule().AssignCharacterModelToEntity(Database.GetDBCharacterModelList()[index]); }); break; } case NetworkMessage.Type.server_removeEntity: { int entityId = data.GetInt(); Map tempMap = Game.GetMap(); if (tempMap == null) { return; } tempMap.RemoveEntity(entityId); break; } case NetworkMessage.Type.server_setControllable: { int controllableEntityId = data.GetInt(); bool isMainEntity = data.GetBool(); Map tempMap = Game.GetMap(); if (tempMap == null) { Network.AddEntityWaitingMessage(controllableEntityId, data); return; } Entity tempEntity = tempMap.GetEntity(controllableEntityId); if (tempEntity == null) { Network.AddEntityWaitingMessage(controllableEntityId, data); return; } PlayerCamera.instance.transform.position = tempEntity.transform.position; Game.GetPlayer().ControllableEntity = tempEntity; if (isMainEntity) { Game.GetPlayer().SetPlayerId(tempEntity.GetId()); } break; } case NetworkMessage.Type.client_movementSnapshot: { int entityId = data.GetInt(); if (Game.GetMap() == null) { return; } Entity entity = Game.GetMap().GetEntity(entityId); if (entity == null) { return; } int time = data.GetInt(); Vector3 position = new Vector3(data.GetFloat(), data.GetFloat(), data.GetFloat()); float rotation = data.GetFloat(); Vector3 inputs = new Vector3(data.GetSByte(), data.GetSByte(), data.GetSByte()); EntityMovement.MovementSnapshot snapshot = new EntityMovement.MovementSnapshot(time, entityId, position, rotation, inputs); entity.GetMovementModule().AddSnapshot(snapshot); break; } case NetworkMessage.Type.server_chatMessage: { ChatUI.MessageType tempChatMessageType = (ChatUI.MessageType)data.GetByte(); int senderId = data.GetInt(); string message = data.GetString(data.GetShort()); if (Game.GetMap() == null) { return; } ChatUI.ReceiveChatMessage(Game.GetMap().GetEntity(senderId), tempChatMessageType, message); break; } case NetworkMessage.Type.server_chatChannelInfo: { bool addChatChannel = data.GetBool(); string chatChannelName = data.GetString(data.GetByte()); if (addChatChannel) { ChatUI.AddChatChannel(chatChannelName); } else { ChatUI.RemoveChatChannel(chatChannelName); } break; } case NetworkMessage.Type.server_entityTeleport: { Vector3 position = new Vector3(data.GetFloat(), data.GetFloat(), data.GetFloat()); float rotation = data.GetFloat(); Game.GetPlayer().ControllableEntity.transform.position = position; Game.GetPlayer().ControllableEntity.GetMovementModule().SetRequestRotation(rotation); break; } case NetworkMessage.Type.server_inventoryItem: { int id = data.GetShort(); int count = data.GetByte(); Game.GetPlayer().SetItem(id, count); break; } case NetworkMessage.Type.server_guildInfo: { int steps = 0; while (!data.EndOfData && steps <= 10) { Player.GuildInfo.TimeInfo type = (Player.GuildInfo.TimeInfo)data.GetByte(); switch (type) { case Player.GuildInfo.TimeInfo.info: { Game.GetPlayer().GetGuildInfo().info = data.GetString(data.GetShort()); break; } case Player.GuildInfo.TimeInfo.announcement: { Game.GetPlayer().GetGuildInfo().announcement = data.GetString(data.GetShort()); break; } case Player.GuildInfo.TimeInfo.name: { Game.GetPlayer().GetGuildInfo().name = data.GetString(data.GetByte()); break; } case Player.GuildInfo.TimeInfo.members: { Player.GuildInfo.Member[] tempMembers = new Player.GuildInfo.Member[data.GetByte()]; for (int i = 0; i < tempMembers.Length; i++) { tempMembers[i] = new Player.GuildInfo.Member(); tempMembers[i].id = data.GetInt(); tempMembers[i].name = data.GetString(data.GetByte()); } Game.GetPlayer().GetGuildInfo().members = new List <Player.GuildInfo.Member>(tempMembers); break; } case Player.GuildInfo.TimeInfo.ranks: { Player.GuildInfo.Rank[] tempRanks = new Player.GuildInfo.Rank[data.GetByte()]; for (int i = 0; i < tempRanks.Length; i++) { tempRanks[i] = new Player.GuildInfo.Rank(); tempRanks[i].id = data.GetInt(); tempRanks[i].name = data.GetString(data.GetByte()); tempRanks[i].isMain = data.GetBool(); tempRanks[i].isBasic = data.GetBool(); tempRanks[i].canMemberInvite = data.GetBool(); tempRanks[i].canMemberRemove = data.GetBool(); tempRanks[i].canRankCreateRemove = data.GetBool(); tempRanks[i].canChangeInfo = data.GetBool(); tempRanks[i].canChangeAnnouncement = data.GetBool(); } Game.GetPlayer().GetGuildInfo().ranks = new List <Player.GuildInfo.Rank>(tempRanks); break; } case Player.GuildInfo.TimeInfo.max: { int memberCount = data.GetByte(); if (memberCount != Game.GetPlayer().GetGuildInfo().members.Count) { //todo error? } for (int i = 0; i < Game.GetPlayer().GetGuildInfo().members.Count; i++) { Game.GetPlayer().GetGuildInfo().members[i].isOnline = data.GetBool(); int rankId = data.GetInt(); Game.GetPlayer().GetGuildInfo().members[i].rank = Game.GetPlayer().GetGuildInfo().ranks.Find(x => x.id == rankId); } break; } default: { Debug.LogError("thefuck?"); break; } } steps++; } if (steps >= 10) { Debug.LogError("critical error happend in guildInfo Message. Maximum steps reached!"); } GuildUI.GuildMessageArrived(); break; } case NetworkMessage.Type.server_setGuild: { int currentId = Game.GetPlayer().GetGuildInfo().id; Game.GetPlayer().GetGuildInfo().id = data.GetInt(); if (Game.GetPlayer().GetGuildInfo().id == -1) { GuildUI.ShowGuild(false); } else if (Game.GetPlayer().GetGuildInfo().id != -1 && currentId == -1 && GuildUI.IsGuildVisible()) { GuildUI.ShowGuild(false); GuildUI.ShowGuild(true); } break; } case NetworkMessage.Type.server_guildListInfo: { Player.GuildInfo[] guildList = new Player.GuildInfo[data.GetShort()]; for (int i = 0; i < guildList.Length; i++) { guildList[i] = new Player.GuildInfo(); guildList[i].id = data.GetInt(); guildList[i].name = data.GetString(data.GetShort()); guildList[i].owner = data.GetString(data.GetByte()); } GuildUI.GuildListArrived(new List <Player.GuildInfo>(guildList)); break; } } }
public static void EntityCheck() { World world = GameManager.Instance.World; Entities = world.Entities.list; for (int i = 0; i < Entities.Count; i++) { Entity _entity = Entities[i]; if (_entity != null) { if (!_entity.IsClientControlled()) { string _name = EntityClass.list[_entity.entityClass].entityClassName; if (BlockIsEnabled) { if (_name == "fallingBlock") { Vector3 _vec = _entity.position; GameManager.Instance.World.RemoveEntity(_entity.entityId, EnumRemoveEntityReason.Despawned); EntityPlayer _douche = world.GetClosestPlayer((int)_vec.x, (int)_vec.y, (int)_vec.z, 10, false); if (_douche == null) { Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Removed falling block id {0} @ {1} {2} {3}", _entity.entityId, (int)_vec.x, (int)_vec.y, (int)_vec.z)); } else { ClientInfo _cInfo = ConnectionManager.Instance.GetClientInfoForEntityId(_douche.entityId); Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Removed falling block id {0} @ {1} {2} {3}. Closest player is {4}", _entity.entityId, (int)_vec.x, (int)_vec.y, (int)_vec.z, _cInfo.playerName)); } } } if (FallingTreeEnabled) { if (_name == "fallingTree") { if (!FallingTree.Contains(_entity.entityId)) { FallingTree.Add(_entity.entityId); } else { GameManager.Instance.World.RemoveEntity(_entity.entityId, EnumRemoveEntityReason.Despawned); FallingTree.Remove(_entity.entityId); Log.Out("[SERVERTOOLS] Entity cleanup: Removed falling tree"); } } } if (Underground) { int y = (int)_entity.position.y; if (y <= -60) { if (_name == "fallingBlock") { GameManager.Instance.World.RemoveEntity(_entity.entityId, EnumRemoveEntityReason.Despawned); Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Removed falling block id {0} from underground", _entity.entityId)); } else { int x = (int)_entity.position.x; int z = (int)_entity.position.z; _entity.SetPosition(new Vector3(x, -1, z)); Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Teleported entity id {0} to the surface @ {1} -1 {2}", _entity.entityId, x, z)); } } } if (Bikes) { if (_name == "minibike") { Vector3 _vec = _entity.position; GameManager.Instance.World.RemoveEntity(_entity.entityId, EnumRemoveEntityReason.Despawned); EntityPlayer _douche = world.GetClosestPlayer((int)_vec.x, (int)_vec.y, (int)_vec.z, 10, false); if (_douche == null) { Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Removed minibike id {0}", _entity.entityId)); } else { ClientInfo _cInfo = ConnectionManager.Instance.GetClientInfoForEntityId(_douche.entityId); Log.Out(string.Format("[SERVERTOOLS] Entity cleanup: Removed minibike id {0}. Closest player is {1}", _entity.entityId, _cInfo.playerName)); } } } } } } }
/// <summary> /// Physics update for the entity /// TODO - fix jump gravity... /// </summary> private void FixedUpdate() { if (!(Entity is Player)) { float gHeight = GetWorldHeight(); if (transform.position.y < gHeight) { transform.position = new Vector3(transform.position.x, gHeight, transform.position.z); } AnimationManager.SetSpeedPercentage(LEPathFinder.CurrentSpeed() / Entity.MovementData.RunSpeed); EntityHealthBar.SetHealthPct(Entity.CombatManager.CurrentHealth / Entity.CombatManager.MaxHealth); UpdateLookAngle(); /* * if (ShouldLook) * { * float angle = Vector3.SignedAngle(Vector3.forward, LookTowardsPointTarget - transform.position, Vector3.up); * Quaternion quat = Quaternion.Euler(new Vector3(0, angle, 0)); * transform.rotation = Quaternion.Slerp(transform.rotation, quat, Time.fixedDeltaTime * LOOK_ROTATION_SPEED); * Entity.SetLookAngle(transform.rotation.eulerAngles.y); * } * * Entity.SetLookAngle(transform.rotation.eulerAngles.y);*/ } Entity.SetPosition(transform.position); //RigidBody.angularVelocity = Vector3.zero; if (GameManager.Paused) { return; } if (IsIdle) { // RigidBody.velocity = Vector3.zero; return; } if (!IsPlayer) { return; } Debug.BeginDeepProfile("le_fixed_update"); EntityHealthBar?.SetHealthPct(Entity.CombatManager.CurrentHealth / Entity.CombatManager.MaxHealth); Vec2i cPos = World.GetChunkPosition(transform.position); /* * * //Check if the current chunk is loaded * if (!GameManager.WorldManager.CRManager.IsCurrentChunkPositionLoaded(cPos)) * { * //If not, keep position dixed with +ve y value, to prevent falling through world. * transform.position = new Vector3(transform.position.x, 6, transform.position.z); * return; * } */ float ground = GetWorldHeight(); float velY = RigidBody.velocity.y; //If we are below the ground, reset position to be at ground level if (transform.position.y < ground) { transform.position = new Vector3(transform.position.x, ground, transform.position.z); } //If our DesiredVelocity is non 0 if (DesiredVelocity != Vector2.zero) { //We check if the terrain we are moving into is valid to move if (CheckMoveableTerrain(transform.position, new Vector3(DesiredVelocity.x, 0, DesiredVelocity.y), 10f)) { //Calculate and set velocity float moveSpeed = IsRunning ? Entity.MovementData.RunSpeed : Entity.MovementData.WalkSpeed; RigidBody.velocity = new Vector3(DesiredVelocity.x * moveSpeed, velY, DesiredVelocity.y * moveSpeed); //inform animation manager of velocity AnimationManager.SetSpeedPercentage(moveSpeed / Entity.MovementData.RunSpeed); } DesiredVelocity = Vector2.zero; AnimationManager.SetSpeedPercentage(0); } else { AnimationManager.SetSpeedPercentage(0); } //The final y coord we will end up at float finalY = transform.position.y; if (finalY < ground) { finalY = ground; } bool IsGrounded = transform.position.y - ground <= 0.1f; //Debug info for player Jumping if (Entity is Player) { DebugGUI.Instance.SetData("jump_vel", VerticalVelocity); DebugGUI.Instance.SetData("onGround", IsGrounded); DebugGUI.Instance.SetData("isJumping", IsJumping); DebugGUI.Instance.SetData("isFalling", IsFalling); DebugGUI.Instance.SetData("groundHeight", ground); } /* * //Falling & jumping code: * * //We change our vertical velocity as required * VerticalVelocity -= 9.81f * Time.fixedDeltaTime; * if(IsGrounded && VerticalVelocity < 0) * { * //if we are grounded, and our velocity is negative: * //If we were falling or jumping, we now land * if (IsJumping || IsFalling) * { * AnimationManager.LandJump(); * } * * VerticalVelocity = 0; * IsJumping = false; * IsFalling = false; * } * * //If the entity is currently grounded and moving down * if (IsGrounded && VerticalVelocity < 0) * { * //If we were falling or jumping, we now land * if (IsJumping || IsFalling) * { * AnimationManager.LandJump(); * } * * velY = 0; * IsJumping = false; * IsFalling = false; * * finalY = ground; * * //maybe we remove this? * // transform.position = new Vector3(transform.position.x, ground, transform.position.z); * * } * else if (IsGrounded && VerticalVelocity > 0) * { * //Update velocity * velY -= 9.81f * Time.fixedDeltaTime; * * //Change height due to velocity + acc * //finalY = transform.position.y + VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; * //if (finalY < ground) * // finalY = ground; * //transform.position = new Vector3(transform.position.x, y, transform.position.z); * }//We are on the ground, and our vertical velocity is small enough to cancle * else if (IsGrounded && Mathf.Abs(VerticalVelocity) < 0.1f) * { * VerticalVelocity = 0; * IsFalling = false; * IsJumping = false; * } * else * { * //We are not grounded * //We are not jumping or falling (yet * if(!(IsJumping || IsFalling)) * { * //If the down is only a little bit down, * //We move to the down position * if (transform.position.y - ground < 0.3f) * { * finalY = ground; * // transform.position = new Vector3(transform.position.x, ground, transform.position.z); * } * else * { * //if we falling further, we set falling to true * IsFalling = true; * AnimationManager.SetFalling(); * } * } * else * { * //If we are not grounded, and we are either jumping or falling, we must update our velocity. * //Update velocity * VerticalVelocity -= 9.81f * Time.fixedDeltaTime; * //Change height due to velocity + acc * finalY = transform.position.y + VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; * if (finalY < ground) * finalY = ground; * // transform.position = new Vector3(transform.position.x, y, transform.position.z); * } * * * /* * //If we are not grounded, but we aren't currently falling or jumping, * //then we must be falling * if (!(IsJumping || IsFalling)) * { * IsFalling = true; * AnimationManager.SetFalling(); * } * * //Update velocity * VerticalVelocity -= 9.81f * Time.fixedDeltaTime; * //Change height due to velocity + acc * float y = transform.position.y + VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; * if (y < ground) * y = ground; * transform.position = * }*/ transform.position = new Vector3(transform.position.x, finalY, transform.position.z); Entity.SetPosition(transform.position); Debug.EndDeepProfile("le_fixed_update"); return; //If we have a specified move direction if (!(MoveDirection == Vector2.zero)) { float tileSpeed = 1; //TODO - get tile speed //Finds correct speed associated with running/walking for this entity float entitySpeed = IsRunning ? Entity.MovementData.RunSpeed : Entity.MovementData.WalkSpeed; AnimationManager.SetSpeedPercentage(entitySpeed / Entity.MovementData.RunSpeed); Vector2 v2Pos = new Vector2(transform.position.x, transform.position.z); Vector2 targetDisp = TargetPosition - v2Pos; float targetMag = targetDisp.magnitude; Vector3 vel = new Vector3(MoveDirection.x, 0, MoveDirection.y) * tileSpeed * entitySpeed; //controller.SimpleMove(vel); float oldVy = RigidBody.velocity.y; //Vector3 vel = new Vector3(MoveDirection.x, 0, MoveDirection.y) * tileSpeed * entitySpeed; RigidBody.velocity = new Vector3(MoveDirection.x, 0, MoveDirection.y) * tileSpeed * entitySpeed; //If the distance the body will move in a frame (|velocity|*dt) is more than the desired amount (target mag) //Then we must scale the velocity down if (RigidBody.velocity.magnitude * Time.fixedDeltaTime > targetMag) { RigidBody.velocity = RigidBody.velocity * targetMag / (Time.fixedDeltaTime * RigidBody.velocity.magnitude); } RigidBody.velocity += Vector3.up * oldVy; Vector3 moveTo = transform.position + vel * Time.fixedDeltaTime * 5; float moveToHeight = GetWorldHeight(moveTo.x, moveTo.z); if (Entity is Player) { Debug.Log("ground: " + ground + " move to" + moveToHeight); } if (moveToHeight > ground) { if ((moveToHeight - ground) * Time.fixedDeltaTime < 0.5f) { transform.position = new Vector3(transform.position.x, moveToHeight, transform.position.z); } } else { transform.position = new Vector3(transform.position.x, moveToHeight, transform.position.z); } if (Entity is Player) { DebugGUI.Instance.SetData("Vel", RigidBody.velocity + " | " + vel); } } else { AnimationManager.SetSpeedPercentage(0); } //If the entity is currently grounded and moving down if (IsGrounded && VerticalVelocity < 0) { //If we were falling or jumping, we now land if (IsJumping || IsFalling) { AnimationManager.LandJump(); } VerticalVelocity = 0; IsJumping = false; IsFalling = false; //maybe we remove this? transform.position = new Vector3(transform.position.x, ground, transform.position.z); } else if (IsGrounded && VerticalVelocity > 0) { //Update velocity VerticalVelocity -= 9.81f * Time.fixedDeltaTime; //Change height due to velocity + acc float y = transform.position.y + VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; if (y < ground) { y = ground; } transform.position = new Vector3(transform.position.x, y, transform.position.z); } else if (IsGrounded && Mathf.Abs(VerticalVelocity) < 0.1f) { VerticalVelocity = 0; IsFalling = false; IsJumping = false; } else { //We are not grounded //If we are not grounded, but we aren't currently falling or jumping, //then we must be falling if (!(IsJumping || IsFalling)) { IsFalling = true; AnimationManager.SetFalling(); } //Update velocity VerticalVelocity -= 9.81f * Time.fixedDeltaTime; //Change height due to velocity + acc float y = transform.position.y + VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; if (y < ground) { y = ground; } transform.position = new Vector3(transform.position.x, y, transform.position.z); } //Check if we are on the ground bool IsOnGround = OnGround(); //Debug info for player Jumping if (Entity is Player) { DebugGUI.Instance.SetData("jump_vel", VerticalVelocity); DebugGUI.Instance.SetData("onGround", IsOnGround); DebugGUI.Instance.SetData("isJumping", IsJumping); DebugGUI.Instance.SetData("isFalling", IsFalling); } /* * if(VerticalVelocity > 0) * { * VerticalVelocity += Physics.gravity.y * Time.fixedDeltaTime; * RigidBody.velocity = RigidBody.velocity + Vector3.up * VerticalVelocity; * if (VerticalVelocity < 0) * VerticalVelocity = 0; * } */ /* * if (IsOnGround && VerticalVelocity < 0) * { * VerticalVelocity = 0; * IsJumping = false; * IsFalling = false; * }*/ /* * //Check if we are off the ground * if (!IsOnGround) * { * //If so, update vertical position and velocity accordingly * VerticalVelocity -= 9.81f * Time.fixedDeltaTime; * Height += VerticalVelocity * Time.fixedDeltaTime - 9.81f * Time.fixedDeltaTime * Time.fixedDeltaTime; * //transform.position += Vector3.up * (VerticalVelocity * Time.fixedDeltaTime+9.81f*Time.fixedDeltaTime*Time.fixedDeltaTime); * //Next, if we are off the ground but not jumping, it must mean we're falling * if (!IsJumping) * { * //If not currently falling, set it to true * if (!IsFalling) * { * IsFalling = true; * AnimationManager.SetFalling(); * } * } * } * else if (VerticalVelocity > 0) { * //If we are on the ground, but our velocity is positive, we must be jumping * VerticalVelocity -= 9.81f * Time.fixedDeltaTime; * Height += VerticalVelocity * Time.fixedDeltaTime; * * } * else if ((IsJumping || IsFalling) && !IsWaitingForJump) * { * //If we are on the ground, but still jumping or falling, set both to false. reset velocity * IsJumping = false; * VerticalVelocity = 0; * IsFalling = false; * //Then play the land animation * AnimationManager.LandJump(); * } * float worldHeight = GetWorldHeight(); * if (transform.position.y < worldHeight) * { * transform.position = new Vector3(transform.position.x, worldHeight, transform.position.z); * VerticalVelocity = 0; * } * * //transform.position = new Vector3(transform.position.x, Height, transform.position.z); */ /* float worldHeight = GetWorldHeight(); * if (transform.position.y < worldHeight) * { * transform.position = new Vector3(transform.position.x, worldHeight, transform.position.z); * VerticalVelocity = 0; * }*/ //Reset variables Entity.MoveEntity(transform.position); Debug.EndDeepProfile("le_fixed_update"); return; }
public static void TeleVehicle(ClientInfo _cInfo, Entity _player, int _vehicle) { int _vehicleId = 0; if (_vehicle == 1) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].BikeId; } else if (_vehicle == 2) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].MiniBikeId; } else if (_vehicle == 3) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].MotorBikeId; } else if (_vehicle == 4) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].JeepId; } else if (_vehicle == 5) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].GyroId; } if (_vehicleId != 0) { List <Entity> Entities = GameManager.Instance.World.Entities.list; for (int i = 0; i < Entities.Count; i++) { Entity _entity = Entities[i]; if (!_entity.IsClientControlled()) { if (_entity.entityId == _vehicleId) { if ((_player.position.x - _entity.position.x) * (_player.position.x - _entity.position.x) + (_player.position.z - _entity.position.z) * (_player.position.z - _entity.position.z) <= Distance * Distance) { if (_entity.AttachedToEntity == false) { _entity.SetPosition(_player.position); string _phrase782; if (!Phrases.Dict.TryGetValue(782, out _phrase782)) { _phrase782 = " found your vehicle and sent it to you."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase782 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); if (Wallet.IsEnabled && Command_Cost >= 1) { Wallet.SubtractCoinsFromWallet(_cInfo.playerId, Command_Cost); } if (_vehicle == 1) { PersistentContainer.Instance.Players[_cInfo.playerId].LastBike = DateTime.Now; } if (_vehicle == 2) { PersistentContainer.Instance.Players[_cInfo.playerId].LastMiniBike = DateTime.Now; } if (_vehicle == 3) { PersistentContainer.Instance.Players[_cInfo.playerId].LastMotorBike = DateTime.Now; } if (_vehicle == 4) { PersistentContainer.Instance.Players[_cInfo.playerId].LastJeep = DateTime.Now; } if (_vehicle == 5) { PersistentContainer.Instance.Players[_cInfo.playerId].LastGyro = DateTime.Now; } PersistentContainer.Instance.Save(); return; } else { string _phrase785; if (!Phrases.Dict.TryGetValue(785, out _phrase785)) { _phrase785 = " found your vehicle but someone else is on it."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase785 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); return; } } } } } string _phrase784; if (!Phrases.Dict.TryGetValue(784, out _phrase784)) { _phrase784 = " could not find your vehicle near by."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase784 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } else { string _phrase783; if (!Phrases.Dict.TryGetValue(783, out _phrase783)) { _phrase783 = " you do not have this vehicle type saved."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + LoadConfig.Chat_Response_Color + _phrase783 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } }
public static void TeleVehicle(ClientInfo _cInfo, Entity _player, int _vehicle) { int _vehicleId = 0; if (_vehicle == 1) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].BikeId; } else if (_vehicle == 2) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].MiniBikeId; } else if (_vehicle == 3) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].MotorBikeId; } else if (_vehicle == 4) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].JeepId; } else if (_vehicle == 5) { _vehicleId = PersistentContainer.Instance.Players[_cInfo.playerId].GyroId; } if (_vehicleId != 0) { List <Entity> Entities = GameManager.Instance.World.Entities.list; for (int i = 0; i < Entities.Count; i++) { Entity _entity = Entities[i]; if (!_entity.IsClientControlled()) { if (_entity.entityId == _vehicleId) { if ((_player.position.x - _entity.position.x) * (_player.position.x - _entity.position.x) + (_player.position.z - _entity.position.z) * (_player.position.z - _entity.position.z) <= Distance * Distance) { if (_entity.AttachedToEntity == false) { _entity.SetPosition(_player.position); if (Wallet.IsEnabled && Command_Cost >= 1) { Wallet.SubtractCoinsFromWallet(_cInfo.playerId, Command_Cost); } if (_vehicle == 1) { PersistentContainer.Instance.Players[_cInfo.playerId].LastBike = DateTime.Now; } if (_vehicle == 2) { PersistentContainer.Instance.Players[_cInfo.playerId].LastMiniBike = DateTime.Now; } if (_vehicle == 3) { PersistentContainer.Instance.Players[_cInfo.playerId].LastMotorBike = DateTime.Now; } if (_vehicle == 4) { PersistentContainer.Instance.Players[_cInfo.playerId].LastJeep = DateTime.Now; } if (_vehicle == 5) { PersistentContainer.Instance.Players[_cInfo.playerId].LastGyro = DateTime.Now; } PersistentContainer.DataChange = true; Phrases.Dict.TryGetValue(493, out string _phrase493); ChatHook.ChatMessage(_cInfo, Config.Chat_Response_Color + _phrase493 + "[-]", -1, Config.Server_Response_Name, EChatType.Whisper, null); return; } else { Phrases.Dict.TryGetValue(496, out string _phrase496); ChatHook.ChatMessage(_cInfo, Config.Chat_Response_Color + _phrase496 + "[-]", -1, Config.Server_Response_Name, EChatType.Whisper, null); return; } } } } } Phrases.Dict.TryGetValue(495, out string _phrase495); ChatHook.ChatMessage(_cInfo, Config.Chat_Response_Color + _phrase495 + "[-]", -1, Config.Server_Response_Name, EChatType.Whisper, null); } else { Phrases.Dict.TryGetValue(494, out string _phrase494); ChatHook.ChatMessage(_cInfo, Config.Chat_Response_Color + _phrase494 + "[-]", -1, Config.Server_Response_Name, EChatType.Whisper, null); } }
public override void Initialize() { base.Initialize(); font = new NezSpriteFont(Content.Load <SpriteFont>("Arial")); // // MIDI sequencer must have processes // sequencer1 = new Sanford.Multimedia.Midi.Sequencer(); sequencer1.clock.Tick += onTick; this.sequencer1.PlayingCompleted += new System.EventHandler(this.HandlePlayingCompleted); this.sequencer1.ChannelMessagePlayed += new System.EventHandler <Sanford.Multimedia.Midi.ChannelMessageEventArgs>(this.HandleChannelMessagePlayed); this.sequencer1.SysExMessagePlayed += new System.EventHandler <Sanford.Multimedia.Midi.SysExMessageEventArgs>(this.HandleSysExMessagePlayed); this.sequencer1.Chased += new System.EventHandler <Sanford.Multimedia.Midi.ChasedEventArgs>(this.HandleChased); this.sequencer1.Stopped += new System.EventHandler <Sanford.Multimedia.Midi.StoppedEventArgs>(this.HandleStopped); // // Default output device (usually 0) // outDevice = new OutputDevice(outDeviceID); //DialogBar db = new DialogBar(-1); //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // mouse entity (used for tracking of clicks) //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn MouseCursor = CreateEntity("mouse"); MouseCursor.AddComponent(new BoxCollider()); MouseCursor.AddComponent(new MouseComponent()); //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // keyboard entity (playing piano manually) //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn MouseCursor = CreateEntity("keyboard"); MouseCursor.AddComponent(new KeyComponent()); //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // Text entity with component (Game name label) //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn TextEntity = CreateEntity("txt"); TextEntity.Transform.Position = new Vector2(10, 20); TextEntity.Transform.Scale = new Vector2(1, 1); txt = new TextComponent(Graphics.Instance.BitmapFont, "MIDI Player", new Vector2(0, 0), Color.White); txt.SetFont(font); TextEntity.AddComponent(txt); //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // Background, with high value render layer //znznznznznznznznznznznznznznznznznznznznznznznznznznznznzn Background = CreateEntity("background", new Vector2(0, 0)); Background.Tag = 90; //SpriteRenderer comp = new SpriteRenderer(Content.Load<Texture2D>("Background")).SetRenderLayer(99); Background.AddComponent(new SpriteRenderer(Content.Load <Texture2D>("Slider/BackgroundMetal")).SetRenderLayer(99)); Background.GetComponent <SpriteRenderer>().SetOrigin(new Vector2(0, 0)); Background.SetPosition(new Vector2(310, 15)); //znznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // Canvas //znznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // int StartX = 10; Entity uiCan = CreateEntity("ui"); canvas = uiCan.AddComponent(new UICanvas()); canvas.IsFullScreen = true; canvas.RenderLayer = -10;//= SCREEN_SPACE_RENDER_LAYER; // // Display for track number // TrackMsg = canvas.Stage.AddElement(new Nez.UI.Label("All Tracks")); TrackMsg.SetPosition(320, 310); TrackMsg.SetSize(100f, 50f); // // Display for channel number // ChnlMsg = canvas.Stage.AddElement(new Nez.UI.Label("All Channels")); ChnlMsg.SetPosition(320, 330); ChnlMsg.SetSize(100f, 50f); AllChannels = -1; // // Display for instrument name // InstrumentMsg = canvas.Stage.AddElement(new Nez.UI.Label("All Channels")); InstrumentMsg.SetPosition(320, 350); InstrumentMsg.SetSize(100f, 50f); // // Dispaly for note number being played // NoteMsg = canvas.Stage.AddElement(new Nez.UI.Label("Piano note played")); NoteMsg.SetPosition(320, 370); NoteMsg.SetSize(100f, 50f); // // Track buttons and channels // for (int i = 0; i < 16; i++) { TrackChanl[i] = -1; TracksInMidi[i] = false; //is track number active in MIDI file TracksPlaying[i] = false; //individual tracks playing (buttons) ChannelsPlaying[i] = true; //they all are playing } // // turn off all buttons // //SetTrackButtonOff(); // // Progress bar // PgBar = canvas.Stage.AddElement(new Nez.UI.ProgressBar(0, 1000, 1, false, Nez.UI.ProgressBarStyle.Create(Color.Green, Color.White))); PgBar.SetPosition(10, StartPos); // // Play button // PlayImageUp = new SpriteDrawable((Content.Load <Texture2D>("Player/play_blk"))); PlayImageDn = new SpriteDrawable((Content.Load <Texture2D>("Player/play_grn"))); PlayBtn = canvas.Stage.AddElement(new ImageButton(PlayImageUp, PlayImageDn)); PlayBtn.SetPosition(StartX, StartPos + 30); PlayBtn.OnClicked += Play; // // Stop button // StopImageUp = new SpriteDrawable((Content.Load <Texture2D>("Player/stop_blk"))); StopImageDn = new SpriteDrawable((Content.Load <Texture2D>("Player/stop_grn"))); StopBtn = canvas.Stage.AddElement(new ImageButton(StopImageUp, StopImageDn)); StopBtn.SetPosition(StartX + 71, StartPos + 30); StopBtn.OnClicked += Stop; // // Load/Eject button (stop playing, look for another MIDI file) // LoadImageUp = new SpriteDrawable((Content.Load <Texture2D>("Player/eject_blk"))); LoadImageDn = new SpriteDrawable((Content.Load <Texture2D>("Player/eject_grn"))); LoadBtn = canvas.Stage.AddElement(new ImageButton(LoadImageUp, LoadImageDn)); LoadBtn.SetPosition(StartX + 110, StartPos + 30); LoadBtn.OnClicked += Load; // //znznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // Systems to process our requests //znznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznznzn // this.AddEntityProcessor(new MouseClickSystem(new Matcher().All(typeof(MouseComponent)))); this.AddEntityProcessor(new KeyClickSystem(new Matcher().All(typeof(KeyComponent)))); this.AddEntityProcessor(new PianoClickSystem(new Matcher().All(typeof(NoteComponent), typeof(PlayingComponent)))); // // Start by loading a file // if (!LoadMidiFile()) { return; } // // Create the Mixer image with buttons, sliders, etc // var Track = new TrackMixerEntity(this, new Vector2(310, 20), canvas, TracksInMidi); // // Create the piano keys on bottom of mixer // var pi00 = new PianoEntity(this, new Vector2(StartX + 245, StartPos + 420), 0); // // Octave 4 is the middle C (note 60), color the keys // HandleOctaveColor(60); }
public void EntityLeave(Entity entity) { EnteredEntities.Remove(entity); entity.SetPosition(WorldEntrance); }
public static void Exec2(ClientInfo _cInfo, EntityPlayer _player) { string _sql = string.Format("SELECT bikeId FROM Players WHERE steamid = '{0}'", _cInfo.playerId); DataTable _result = SQL.TQuery(_sql); int _bikeId; int.TryParse(_result.Rows[0].ItemArray.GetValue(0).ToString(), out _bikeId); _result.Dispose(); if (_bikeId != 0) { List <Entity> Entities = GameManager.Instance.World.Entities.list; for (int i = 0; i < Entities.Count; i++) { Entity _entity = Entities[i]; string _name = EntityClass.list[_entity.entityClass].entityClassName; Type _class = EntityClass.list[_entity.entityClass].classname.BaseType; Log.Out(string.Format("entity name = {0}/ class base type = {1}", _name, _class)); if (_name == "minibike") { if ((_player.position.x - _entity.position.x) * (_player.position.x - _entity.position.x) + (_player.position.z - _entity.position.z) * (_player.position.z - _entity.position.z) <= 50 * 50) { if (_entity.entityId == _bikeId) { if (_entity.AttachedToEntity == false) { _entity.SetPosition(_player.position); string _phrase782; if (!Phrases.Dict.TryGetValue(782, out _phrase782)) { _phrase782 = "found your bike and sent it to you."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + _phrase782 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); if (Wallet.IsEnabled && Command_Cost >= 1) { Wallet.SubtractCoinsFromWallet(_cInfo.playerId, Command_Cost); } _sql = string.Format("UPDATE Players SET lastBike = '{0}' WHERE steamid = '{1}'", DateTime.Now, _cInfo.playerId); SQL.FastQuery(_sql); return; } else { string _phrase785; if (!Phrases.Dict.TryGetValue(785, out _phrase785)) { _phrase785 = "found your bike but someone else is on it."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + _phrase785 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); return; } } } } } string _phrase784; if (!Phrases.Dict.TryGetValue(784, out _phrase784)) { _phrase784 = "could not find your bike near by."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + _phrase784 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } else { string _phrase783; if (!Phrases.Dict.TryGetValue(783, out _phrase783)) { _phrase783 = "you do not have a bike saved."; } ChatHook.ChatMessage(_cInfo, ChatHook.Player_Name_Color + _cInfo.playerName + _phrase783 + "[-]", _cInfo.entityId, LoadConfig.Server_Response_Name, EChatType.Whisper, null); } }
/// <summary> /// Physics update for the entity /// /// </summary> private void FixedUpdate() { //RigidBody.angularVelocity = Vector3.zero; if (GameManager.Paused) { return; } if (IsIdle) { return; } Debug.BeginDeepProfile("le_fixed_update"); if (!(Entity is Player)) { DebugGUI.Instance.SetData("ent", GameManager.Paused + "_" + IsIdle + "_" + MoveDirection); if (MiscMaths.DistanceSqr(transform.position, GameManager.PlayerManager.Player.Position) > (World.ChunkSize * 4) * (World.ChunkSize * 4)) { IsIdle = true; } } EntityHealthBar.SetHealthPct(Entity.CombatManager.CurrentHealth / Entity.CombatManager.MaxHealth); if (transform.position.y < 0) { transform.position = new Vector3(transform.position.x, 0, transform.position.z); } Vec2i cPos = World.GetChunkPosition(transform.position); //Check if the current chunk is loaded if (!GameManager.WorldManager.CRManager.IsCurrentChunkPositionLoaded(cPos)) { //If not, keep position dixed with +ve y value, to prevent falling through world. transform.position = new Vector3(transform.position.x, 1, transform.position.z); } //If we have a specified move direction if (MoveDirection != Vector2.zero) { float tileSpeed = 1; //TODO - get tile speed //Finds correct speed associated with running/walking for this entity float entitySpeed = IsRunning?Entity.MovementData.RunSpeed:Entity.MovementData.WalkSpeed; AnimationManager.SetSpeedPercentage(entitySpeed / Entity.MovementData.RunSpeed); Vector2 v2Pos = new Vector2(transform.position.x, transform.position.z); Vector2 targetDisp = TargetPosition - v2Pos; float targetMag = targetDisp.magnitude; Vector3 vel = new Vector3(MoveDirection.x, 0, MoveDirection.y) * tileSpeed * entitySpeed; RigidBody.velocity = new Vector3(MoveDirection.x, 0, MoveDirection.y) * tileSpeed * entitySpeed; //If the distance the body will move in a frame (|velocity|*dt) is more than the desired amount (target mag) //Then we must scale the velocity down if (RigidBody.velocity.magnitude * Time.fixedDeltaTime > targetMag) { RigidBody.velocity = RigidBody.velocity * targetMag / (Time.fixedDeltaTime * RigidBody.velocity.magnitude); } if (Entity is Player) { DebugGUI.Instance.SetData("Vel", RigidBody.velocity + " | " + vel); } } else { AnimationManager.SetSpeedPercentage(0); } //If we have a specified look direction if (LookTowards != Vector3.zero) { float angle = Vector3.SignedAngle(Vector3.forward, LookTowards - transform.position, Vector3.up); Quaternion quat = Quaternion.Euler(new Vector3(0, angle, 0)); transform.rotation = Quaternion.Slerp(transform.rotation, quat, Time.fixedDeltaTime * LOOK_ROTATION_SPEED); Entity.SetLookAngle(transform.rotation.eulerAngles.y); } //Check if we are on the ground bool IsOnGround = OnGround(); //Debug info for player Jumping if (Entity is Player) { DebugGUI.Instance.SetData("jump_vel", VerticalVelocity); DebugGUI.Instance.SetData("onGround", IsOnGround); DebugGUI.Instance.SetData("isJumping", IsJumping); DebugGUI.Instance.SetData("isFalling", IsFalling); } //Check if we are off the ground if (!IsOnGround) { //If so, update vertical position and velocity accordingly VerticalVelocity -= 9.81f * Time.fixedDeltaTime; transform.position += Vector3.up * VerticalVelocity * Time.fixedDeltaTime; //Next, if we are off the ground but not jumping, it must mean we're falling if (!IsJumping) { //If not currently falling, set it to true if (!IsFalling) { IsFalling = true; AnimationManager.SetFalling(); } } } else if (VerticalVelocity > 0) { //If we are on the ground, but our velocity is positive, we must be jumping VerticalVelocity -= 9.81f * Time.fixedDeltaTime; transform.position += Vector3.up * VerticalVelocity * Time.fixedDeltaTime; } else if ((IsJumping || IsFalling) && !IsWaitingForJump) { //If we are on the ground, but still jumping or falling, set both to false. reset velocity IsJumping = false; VerticalVelocity = 0; IsFalling = false; //Then play the land animation AnimationManager.LandJump(); } //Reset variables LookTowards = Vector3.zero; MoveDirection = Vector2.zero; Entity.SetPosition(transform.position); Debug.EndDeepProfile("le_fixed_update"); return; }
/// <summary> /// used to move an entity from one subworld to another /// </summary> /// <param name="entity"></param> /// <param name="newSubworldID"></param> /// <param name="newPosition"></param> public void MoveEntity(Entity entity, int newSubworldID, Vec2i newPosition) { Vec2i oldChunk = World.GetChunkPosition(entity.Position); bool succesful = false; if (EntitiesByLocation.TryGetValue(entity.CurrentSubworldID, out Dictionary <Vec2i, List <int> > subworldEnts)) { if (subworldEnts.TryGetValue(oldChunk, out List <int> entIds)) { //if this entity is here, we remove them if (entIds.Contains(entity.ID)) { entIds.Remove(entity.ID); succesful = true; } } } if (!succesful) { Debug.LogError("Could not find old location of entity: " + entity); throw new System.Exception("loool"); } int id = entity.ID; //get world ID and chunk position Vec2i cPos = World.GetChunkPosition(newPosition); if (!EntitiesByLocation.ContainsKey(newSubworldID)) { EntitiesByLocation.Add(newSubworldID, new Dictionary <Vec2i, List <int> >()); } if (!EntitiesByLocation[newSubworldID].ContainsKey(cPos)) { EntitiesByLocation[newSubworldID].Add(cPos, new List <int>()); } EntitiesByLocation[newSubworldID][cPos].Add(id); Subworld sw = World.Instance.GetSubworld(newSubworldID); if (sw != null) { sw.AddEntity(entity); } entity.SetSubworld(newSubworldID); entity.SetPosition(newPosition.AsVector3()); entity.SetLastChunk(cPos); int loadedSubworldID = Subworld == null ? -1 : Subworld.SubworldID; //If the current entity is loaded... if (IsEntityLoaded(entity.ID)) { Debug.Log("1"); //Check if the new position is loaded, if not then we unload the entity if (!LoadedChunks.Contains(cPos) || (entity.CurrentSubworldID != loadedSubworldID)) { Debug.Log("2"); //If the new position isn't loaded, then we must unload the entity //If correct chunk position is loaded, but wrong world, we also unload UnloadEntity(entity.GetLoadedEntity(), false); //If the entity is now in a subworld after being unloaded, //we must check if they are close enough to the player to have a slow update. if (entity.CurrentSubworldID != -1) { if (sw != null) { //We get the entrance, and check if the relvent chunk is loaded Vec2i entranceChunk = World.GetChunkPosition(sw.ExternalEntrancePos); //If it is, then we make sure we continue to run slow ticks on the unloaded entity if (LoadedChunks.Contains(entranceChunk)) { UnloadedUpdatableEntities.Add(entity.ID); } } } } } else { if (LoadedChunks.Contains(cPos) && (entity.CurrentSubworldID == loadedSubworldID)) { LoadEntity(entity); } } }
public Entity AddEntityAt(Entity e, float tx, float ty) { AddEntity(e); e.SetPosition(tx * Game.Unit, ty * Game.Unit); return(e); }
public override bool ParseBytesAndExecute(byte[] data) { int len = 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 4 + 24 + 4 + 4 + 4 + 4; if (data.Length < len) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad initial length!"); return(false); } byte type = data[0]; long EID1 = Utilities.BytesToLong(Utilities.BytesPartial(data, 1, 8)); long EID2 = Utilities.BytesToLong(Utilities.BytesPartial(data, 1 + 8, 8)); long JID = Utilities.BytesToLong(Utilities.BytesPartial(data, 1 + 8 + 8, 8)); if (TheClient.TheRegion.GetJoint(JID) != null) { // If we already know this joint, just keep on going. return(true); } Entity pe1 = TheClient.TheRegion.GetEntity(EID1); Entity pe2 = TheClient.TheRegion.GetEntity(EID2); if (pe1 == null) { SysConsole.Output(OutputType.WARNING, "Joint Packet: Invalid EID-1 " + EID1); return(false); } if (pe2 == null) { SysConsole.Output(OutputType.WARNING, "Joint Packet: Invalid EID-2 " + EID2); return(false); } Location pos1 = Location.FromDoubleBytes(data, 1 + 8 + 8 + 8); float qx1 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24, 4)); float qy1 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4, 4)); float qz1 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4, 4)); float qw1 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4, 4)); BEPUutilities.Quaternion quat1 = new BEPUutilities.Quaternion(qx1, qy1, qz1, qw1); pe1.SetPosition(pos1); pe1.SetOrientation(quat1); Location pos2 = Location.FromDoubleBytes(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 4); float qx2 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 24 + 4 + 4 + 4 + 4, 4)); float qy2 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 24 + 4 + 4 + 4 + 4, 4)); float qz2 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 24 + 4 + 4 + 4 + 4, 4)); float qw2 = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 24 + 4 + 4 + 4 + 4, 4)); BEPUutilities.Quaternion quat2 = new BEPUutilities.Quaternion(qx2, qy2, qz2, qw2); pe1.SetPosition(pos1); pe1.SetOrientation(quat1); pe2.SetPosition(pos2); pe2.SetOrientation(quat2); if (type == 0) { if (data.Length != len + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location pos = Location.FromDoubleBytes(data, len); JointBallSocket jbs = new JointBallSocket((PhysicsEntity)pe1, (PhysicsEntity)pe2, pos) { JID = JID }; TheClient.TheRegion.AddJoint(jbs); return(true); } else if (type == 1) { if (data.Length != len + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location dir = Location.FromDoubleBytes(data, len); JointSlider js = new JointSlider((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir) { JID = JID }; TheClient.TheRegion.AddJoint(js); return(true); } else if (type == 2) { if (data.Length != len + 4 + 4 + 24 + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } float min = Utilities.BytesToFloat(Utilities.BytesPartial(data, len, 4)); float max = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 4, 4)); Location ent1pos = Location.FromDoubleBytes(data, len + 4 + 4); Location ent2pos = Location.FromDoubleBytes(data, len + 4 + 4 + 24); JointDistance jd = new JointDistance((PhysicsEntity)pe1, (PhysicsEntity)pe2, min, max, ent1pos, ent2pos) { JID = JID }; TheClient.TheRegion.AddJoint(jd); return(true); } else if (type == 3) { if (data.Length != len + 24 + 1) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location axis = Location.FromDoubleBytes(data, len); bool mode = data[len + 24] == 1; JointPullPush jpp = new JointPullPush((PhysicsEntity)pe1, (PhysicsEntity)pe2, axis, mode) { JID = JID }; TheClient.TheRegion.AddJoint(jpp); return(true); } else if (type == 4) { if (data.Length != len) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } JointForceWeld jfw = new JointForceWeld(pe1, pe2) { JID = JID }; TheClient.TheRegion.AddJoint(jfw); return(true); } else if (type == 5) { if (data.Length != len + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location dir = Location.FromDoubleBytes(data, len); JointSpinner js = new JointSpinner((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir) { JID = JID }; TheClient.TheRegion.AddJoint(js); return(true); } else if (type == 6) { if (data.Length != len + 24 + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location a1 = Location.FromDoubleBytes(data, len); Location a2 = Location.FromDoubleBytes(data, len + 24); JointTwist jt = new JointTwist((PhysicsEntity)pe1, (PhysicsEntity)pe2, a1, a2) { JID = JID }; TheClient.TheRegion.AddJoint(jt); return(true); } else if (type == 7) { if (data.Length != len) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } JointWeld jw = new JointWeld((PhysicsEntity)pe1, (PhysicsEntity)pe2) { JID = JID }; TheClient.TheRegion.AddJoint(jw); return(true); } else if (type == 8) { if (data.Length != len + 24 + 1) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location dir = Location.FromDoubleBytes(data, len); bool issteering = data[len + 24] == 1; JointVehicleMotor jm = new JointVehicleMotor((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir, issteering) { JID = JID }; TheClient.TheRegion.AddJoint(jm); return(true); } else if (type == 9) { if (data.Length != len + 24 + 24 + 24 + 4 + 4) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location cpos1 = Location.FromDoubleBytes(data, len); Location cpos2 = Location.FromDoubleBytes(data, len + 24); Location axis = Location.FromDoubleBytes(data, len + 24 + 24); float min = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 24 + 24 + 24, 4)); float max = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 24 + 24 + 24 + 4, 4)); JointLAxisLimit jlal = new JointLAxisLimit((PhysicsEntity)pe1, (PhysicsEntity)pe2, min, max, cpos1, cpos2, axis) { JID = JID }; TheClient.TheRegion.AddJoint(jlal); return(true); } else if (type == 10) { if (data.Length != len + 24 + 24) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } Location hinge = Location.FromDoubleBytes(data, len); Location twist = Location.FromDoubleBytes(data, len + 24); JointSwivelHinge jlal = new JointSwivelHinge((PhysicsEntity)pe1, (PhysicsEntity)pe2, hinge, twist) { JID = JID }; TheClient.TheRegion.AddJoint(jlal); return(true); } else if (type == 11) { if (data.Length != len + 4) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } float height = Utilities.BytesToFloat(Utilities.BytesPartial(data, len, 4)); ConstWheelStepUp cwsu = new ConstWheelStepUp((PhysicsEntity)pe1, height) { JID = JID }; TheClient.TheRegion.AddJoint(cwsu); return(true); } else if (type == 12) { if (data.Length != len + 4 + 1) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } ConnectorBeam cb = new ConnectorBeam() { One = pe1, Two = pe2, color = System.Drawing.Color.FromArgb(Utilities.BytesToInt(Utilities.BytesPartial(data, len, 4))), JID = JID, type = (BeamType)data[len + 4] }; TheClient.TheRegion.AddJoint(cb); return(true); } else if (type == 13) { if (data.Length != len) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } JointFlyingDisc jfd = new JointFlyingDisc((PhysicsEntity)pe1) { JID = JID }; TheClient.TheRegion.AddJoint(jfd); return(true); } else if (type == 14) { if (data.Length != len) { SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!"); return(false); } JointNoCollide jnc = new JointNoCollide((PhysicsEntity)pe1, (PhysicsEntity)pe2) { JID = JID }; TheClient.TheRegion.AddJoint(jnc); return(true); } else { SysConsole.Output(OutputType.WARNING, "Unknown joint type " + type); return(false); } }
public void EntityEnter(uint id, Entity.Type type, uint subType, Vector3 position, float direction) { Entity entity = null; switch (type) { case Entity.Type.Player: case Entity.Type.NPC: { RoleInfo info = Core.Database.GetRoleInfo(subType); GameObject go = Core.Database.LoadResource("Roles/" + info.res); go.transform.localScale = Vector3.one * info.scale; Role role = go.AddComponent <Role>(); go.AddComponent <RoleAnimator>(); RoleAgent agent = go.AddComponent <RoleAgent>(); agent.RoleId = id; CapsuleCollider collider = go.AddComponent <CapsuleCollider>(); collider.radius = 0.5f; collider.height = 2; collider.center = new Vector3(0, 1.1f, 0); if (Core.Account.role == null) { Core.Account.role = role; m_camera.GetComponent <CameraController>().target = go.transform; go.AddComponent <RoleController>(); Rigidbody rigidbody = go.AddComponent <Rigidbody>(); rigidbody.freezeRotation = true; rigidbody.useGravity = false; } entity = role; } break; case Entity.Type.Teleporter: { GameObject go = Core.Database.LoadResource("Entities/Teleporter"); entity = go.AddComponent <Teleporter>(); } break; case Entity.Type.Item: { GameObject go = Core.Database.LoadResource("Entities/Bottle"); entity = go.AddComponent <DropItem>(); } break; default: break; } if (entity != null) { entity.SetInfo(id, type, subType); entity.SetPosition(position); entity.SetDirection(direction); AddEntity(entity); } }
public override void Execute(List <string> _params, CommandSenderInfo _senderInfo) { try { if (_params.Count != 2 && _params.Count != 4) { SdtdConsole.Instance.Output(string.Format("Wrong number of arguments, expected 2, 4, found {0}", _params.Count)); return; } if (_params.Count == 2) { int _entityId1; if (!int.TryParse(_params[0], out _entityId1)) { SdtdConsole.Instance.Output(string.Format("Invalid entity id value: {0}", _entityId1)); return; } int _entityId2; if (!int.TryParse(_params[1], out _entityId2)) { SdtdConsole.Instance.Output(string.Format("Invalid entity id value: {0}", _entityId2)); return; } Entity Entity1 = GameManager.Instance.World.Entities.dict[_entityId1]; if (Entity1 == null) { SdtdConsole.Instance.Output(string.Format("Entity not found: {0}", _entityId1)); return; } Entity Entity2 = GameManager.Instance.World.Entities.dict[_entityId2]; if (Entity2 == null) { SdtdConsole.Instance.Output(string.Format("Entity not found: {0}", _entityId2)); return; } if (Entity1.IsClientControlled()) { SdtdConsole.Instance.Output(string.Format("Entity with id {0} can not be a player. Use a different command for teleporting players", _entityId1)); return; } Entity1.SetPosition(Entity2.position); SdtdConsole.Instance.Output(string.Format("Teleported entity {0} to entity {1} located at {2} {3} {4}", _entityId1, _entityId2, (int)Entity2.position.x, (int)Entity2.position.y, (int)Entity2.position.z)); } if (_params.Count == 4) { int _entityId; if (!int.TryParse(_params[0], out _entityId)) { SdtdConsole.Instance.Output(string.Format("Invalid entityId value: {0}", _entityId)); return; } Entity Entity = GameManager.Instance.World.Entities.dict[_entityId]; if (Entity == null) { SdtdConsole.Instance.Output(string.Format("Invalid entityId. Entity not found: {0}", _entityId)); return; } if (Entity.IsClientControlled()) { SdtdConsole.Instance.Output(string.Format("Entity with id {0} can not be a player. Use a different command for teleporting players", _entityId)); return; } int _x, _y, _z; if (!int.TryParse(_params[1], out _x)) { SdtdConsole.Instance.Output(string.Format("Invalid entityId value: {0}", _x)); return; } if (!int.TryParse(_params[2], out _y)) { SdtdConsole.Instance.Output(string.Format("Invalid entityId value: {0}", _y)); return; } if (!int.TryParse(_params[3], out _z)) { SdtdConsole.Instance.Output(string.Format("Invalid entityId value: {0}", _z)); return; } Entity.SetPosition(new UnityEngine.Vector3(_x, _y, _z)); SdtdConsole.Instance.Output(string.Format("Teleported entity {0} to {1} {2} {3}", _entityId, _x, _y, _z)); } } catch (Exception e) { Log.Out(string.Format("[SERVERTOOLS] Error in EntityTeleportConsole.Execute: {0}", e)); } }
private static void StandardInit(Entity ent, string name, int tileSize, float scale, Vector2 pos) { ent.Name = name; ent.Scale = scale; ent.TileSize = tileSize; ent.SetPosition(pos); }
static GameObject Spawn(GameObject prefab, Tile origin, Quaternion rotation, Transform parent = null) { GameObject g = Object.Instantiate(prefab, origin.position, rotation); PCGEntityData data = g.GetComponent <PCGEntityData>(); Entity entity = g.GetComponentInChildren <Entity>(); if (data == null) { Debug.LogWarning("'" + prefab.name + "' is missing a PCGEntityData-component!", prefab); return(g); } if (data.subEntities.Length > 0) { for (int i = 0; i < data.subEntities.Length; i++) { if (data.subEntities[i].ignoreSpawnProbability || Synched.Next(0f, 1f) <= _region.template.subEntitiyDensities[(int)data.subEntities[i].type]) { //spawn random object from list //randomize offset from parameters //randomize rotation from parameters relative to subentity rotation //parent under root, IMPORTANT, subentity placeholder object will be removed GameObject sg = Object.Instantiate( data.subEntities[i].prefabs.Random(), data.subEntities[i].transform.position + new Vector3( Synched.Next(-data.subEntities[i].spawnOffset.x, data.subEntities[i].spawnOffset.x), Synched.Next(-data.subEntities[i].spawnOffset.y, data.subEntities[i].spawnOffset.y), Synched.Next(-data.subEntities[i].spawnOffset.z, data.subEntities[i].spawnOffset.z)), Quaternion.Euler( Synched.Next(0, data.subEntities[i].rotationOffset.x), Synched.Next(0, data.subEntities[i].rotationOffset.y), Synched.Next(0, data.subEntities[i].rotationOffset.z)) * data.subEntities[i].transform.rotation, g.transform); //randomize scale - uniformly float scale = Synched.Next(-data.subEntities[i].scaleVariance, data.subEntities[i].scaleVariance); sg.transform.localScale += new Vector3(scale, scale, scale); } //cleanup junk Object.Destroy(data.subEntities[i].gameObject); } } //this is in f*****g world space jfc //gonna need to transform this relative to rotation of entity somehow //... later origin.SetStatus(data.blocksTile ? TileStatus.Blocked : TileStatus.Vacant); origin.SetBlocksLineOfSight(data.blocksLineOfSight); //for (int x = data.negativeSize.x; x <= data.positiveSize.x; x++) //{ // for (int z = data.negativeSize.y; z <= data.positiveSize.y; z++) // { // Tile t = Grid.Get(origin.x + x, origin.z + z); // if (t != null) // { // t.SetStatus(data.blocksTile ? TileStatus.Blocked : TileStatus.Vacant); // t.SetBlocksLineOfSight(data.blocksLineOfSight); // } // } //} entity?.SetPosition(origin); //cleanup junk Object.Destroy(data); return(g); }
public static void Exec(ClientInfo _cInfo) { EntityPlayer _player = GameManager.Instance.World.Players.dict[_cInfo.entityId]; if (_player.AttachedToEntity != null) { int _counter = 0; int _claimSize = GameStats.GetInt(EnumGameStats.LandClaimSize) / 2; PersistentPlayerList _persistentPlayerList = GameManager.Instance.GetPersistentPlayerList(); PersistentPlayerData _persistentPlayerData = _persistentPlayerList.GetPlayerData(_cInfo.playerId); List <Vector3i> _blocks = _persistentPlayerData.LPBlocks; for (int i = 0; i < _blocks.Count; i++) { Vector3i _vec3i = _blocks[i]; if ((_vec3i.x - _player.position.x) * (_vec3i.x - _player.position.x) + (_vec3i.z - _player.position.z) * (_vec3i.z - _player.position.z) <= _claimSize * _claimSize) { string _phrase781; if (!Phrases.Dict.TryGetValue(781, out _phrase781)) { _phrase781 = "{PlayerName} saved your current bike for retrieval."; } _phrase781 = _phrase781.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase781), Config.Server_Response_Name, false, "ServerTools", false)); PersistentContainer.Instance.Players[_cInfo.playerId, true].BikeId = _player.AttachedToEntity.entityId; PersistentContainer.Instance.Save(); } else { _counter++; } } if (_counter == _blocks.Count) { string _phrase780; if (!Phrases.Dict.TryGetValue(780, out _phrase780)) { _phrase780 = "{PlayerName} you do not own this land. You can only save your bike inside your own claimed space."; } _phrase780 = _phrase780.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase780), Config.Server_Response_Name, false, "ServerTools", false)); } } else { Player p = PersistentContainer.Instance.Players[_cInfo.playerId, false]; if (p != null) { if (p.BikeId != 0) { List <Entity> Entities = GameManager.Instance.World.Entities.list; int _counter = 0; bool Other = false, Found = false; for (int i = 0; i < Entities.Count; i++) { _counter++; Entity _entity = Entities[i]; string _name = EntityClass.list[_entity.entityClass].entityClassName; if (_name == "minibike") { if ((_player.position.x - _entity.position.x) * (_player.position.x - _entity.position.x) + (_player.position.z - _entity.position.z) * (_player.position.z - _entity.position.z) <= 50 * 50) { if (_entity.entityId == p.BikeId) { if (_entity.AttachedToEntity == false) { _entity.SetPosition(_player.position); string _phrase782; if (!Phrases.Dict.TryGetValue(782, out _phrase782)) { _phrase782 = "{PlayerName} found your bike and sent it to you."; } _phrase782 = _phrase782.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase782), Config.Server_Response_Name, false, "ServerTools", false)); int _oldCoins = PersistentContainer.Instance.Players[_cInfo.playerId, false].PlayerSpentCoins; PersistentContainer.Instance.Players[_cInfo.playerId, true].PlayerSpentCoins = _oldCoins - Command_Cost; PersistentContainer.Instance.Players[_cInfo.playerId, true].LastBike = DateTime.Now; PersistentContainer.Instance.Save(); Found = true; } else { string _phrase785; if (!Phrases.Dict.TryGetValue(785, out _phrase785)) { _phrase785 = "{PlayerName} found your bike but someone else is on it."; } _phrase785 = _phrase785.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase785), Config.Server_Response_Name, false, "ServerTools", false)); Other = true; } } } } } if (_counter == Entities.Count && !Other && !Found) { string _phrase784; if (!Phrases.Dict.TryGetValue(784, out _phrase784)) { _phrase784 = "{PlayerName} could not find your bike near by."; } _phrase784 = _phrase784.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase784), Config.Server_Response_Name, false, "ServerTools", false)); } } else { string _phrase783; if (!Phrases.Dict.TryGetValue(783, out _phrase783)) { _phrase783 = "{PlayerName} you do not have a bike saved."; } _phrase783 = _phrase783.Replace("{PlayerName}", _cInfo.playerName); _cInfo.SendPackage(new NetPackageGameMessage(EnumGameMessages.Chat, string.Format("{0}{1}[-]", Config.Chat_Response_Color, _phrase783), Config.Server_Response_Name, false, "ServerTools", false)); } } } }