public void ConnectToLobby(string lobbyFriendlyName, string clientVersion) { double truncatedServerVersion = 0; double truncatedClientVersion = 0; if (!TryTruncateVersionString(ServerVersion, out truncatedServerVersion) || !TryTruncateVersionString(clientVersion, out truncatedClientVersion) || truncatedClientVersion < truncatedServerVersion) { Clients.Caller.SendAsync("UpdateState", JsonConvert.SerializeObject(CommonUnityViews.GenerateInvalidVersionView())); return; } try { Lobby lobby = GameManager.GetLobby(lobbyFriendlyName); if (lobby != null) { LeaveAllGroups(); Groups.AddToGroupAsync(Context.ConnectionId, lobby.LobbyId); UnityView view = lobby.GetActiveUnityView(returnNullIfNoChange: false); // SignalR's serialization is abysmal and client has no insight into the issue. pull serialization out. Clients.Caller.SendAsync("UpdateState", JsonConvert.SerializeObject(view)); Clients.Caller.SendAsync("ConfigureMetadata", JsonConvert.SerializeObject(lobby.ConfigMetaData)); } } catch (Exception e) { Console.Error.WriteLine(e); } }
public void SetState(ControlState state) { if (state == this.state) { return; } if (state == ControlState.BUILDING_GAME) { UnityView.ReleaseHumanoid(this); if (homonid != null) { homonid.ReleaseControl(); cursor.transform.position = homonid.transform.position; } state = ControlState.BUILDING_GAME; cursor.AssertControl(actions, this); UnityView.viewer.topDownActionCam.SetFocus(cursor.gameObject.GetComponent <CameraFocus> ()); following = true; //CREATE BUILD MENu List <MenuButton> buttons = new List <MenuButton>(); foreach (var building in UnityView.viewer.buildings) { MenuButton button = new MenuButton(); button.text = building.name; button.onClick = () => { if (cursorContent != null) { Transform newThing = Transform.Instantiate(cursorContent); newThing.position = cursorContent.position; newThing.rotation = cursorContent.rotation; } }; button.onFocus = () => { if (cursorContent != null) { GameObject.Destroy(cursorContent.gameObject); } Transform newBuilding = Transform.Instantiate(building); cursorContent = newBuilding; newBuilding.SetParent(cursor.transform); newBuilding.localPosition = Vector3.zero; }; buttons.Add(button); } UnityView.viewer.menu.SetupMenu(inputDevice, buttons); } else if (state == ControlState.ACTION_GAME) { if (entity != null) { state = ControlState.ACTION_GAME; cursor.ReleaseControl(); UnityView.ControlHumanoid(this); } } else { Debug.LogError("What the f**k state is this you idiot!?!?! " + state); } }
public override void EnterView(UnityView view) { base.EnterView(view); UnityView = view; UpdateHandlers(); CallHandlers(); }
public static void SetParent(this UnityView view) { if (view.Entity.hasViewData && view.Entity.viewData.parentID != "") { view.transform.SetParent(ScenePositionUtility.Instance.GetParent(view.Entity.viewData.parentID), false); } }
public QueryGameState( Lobby lobby, Func <User, List <Q>, UserPrompt> queryUserPromptGenerator, List <Q> queryObjects, Action <List <Q> > queryExitListener, Func <UserSubForm, T> answerExtractor, UnityView queryUnityView, List <User> queriedUsers, TimeSpan?queryTime = null) : base(lobby) { this.PromptGenerator = queryUserPromptGenerator; this.ObjectList = queryObjects; this.AnswerExtractor = answerExtractor; this.Entrance.AddExitListener(() => { StartingTime = DateTime.UtcNow; }); SelectivePromptUserState queryUserState = new SelectivePromptUserState( usersToPrompt: queriedUsers ?? lobby.GetAllUsers().ToList(), promptGenerator: this.InternalPromptGenerator, formSubmitHandler: this.FormSubmitHandler, userTimeoutHandler: this.FormTimeoutHandler, maxPromptDuration: queryTime, exit: new WaitForUsers_StateExit(lobby: lobby)); this.Entrance.Transition(queryUserState); queryUserState.Transition(this.Exit); queryUserState.AddExitListener(() => queryExitListener(this.ObjectList)); this.UnityView = queryUnityView; }
/// <summary> /// This function contains the bulk of the work and gets run on a loop. /// </summary> private void DoWork(object _) { while (GameManager.AbandonedLobbyIds.TryTake(out string lobbyId)) { UnityHubNotifier.Clients.Group(lobbyId).SendAsync("LobbyClose"); } foreach (Lobby lobby in GameManager.GetLobbies()) { try { UnityView view = lobby.GetActiveUnityView(returnNullIfNoChange: true); if (view != null) { // SignalR's serialization is abysmal and client has no insight into the issue. pull serialization out. UnityHubNotifier.Clients.Group(lobby.LobbyId).SendAsync("UpdateState", JsonConvert.SerializeObject(view)); } bool needToRefreshMetadata = lobby.ConfigMetaData?.Refresh() ?? false; if (needToRefreshMetadata) { UnityHubNotifier.Clients.Group(lobby.LobbyId).SendAsync("ConfigureMetadata", lobby.ConfigMetaData); } } catch (Exception e) { GameManager.ReportGameError(ErrorType.UnityClient, lobby.LobbyId, null, e); } } }
/// <summary> /// Returns the unity view that needs to be potentially sent to the clients. /// </summary> /// <returns>The active unity view</returns> public UnityView GetActiveUnityView(bool returnNullIfNoChange) { UnityView currentView = this.CurrentGameState?.GetActiveUnityView(); Legacy_UnityView currentLegacyView = this.CurrentGameState?.GetActiveLegacyUnityView(); /*if (currentView != null && currentLegacyView != null) * { * throw new Exception("Gamestate did not properly setup views"); * }*/ if (currentLegacyView != null) { if (!returnNullIfNoChange || currentLegacyView.Refresh()) { return(new UnityView(currentLegacyView)); } } else if (currentView != null) { if (!returnNullIfNoChange) { return(currentView); } else if (this.CurrentGameState?.UnityViewDirty ?? false) { this.CurrentGameState.UnityViewDirty = false; return(currentView); } } return(null); }
public static void SetSpawnPosition(this UnityView view) { if (view.Entity.hasViewData && view.Entity.viewData.spawnPositionID.Length > 0) { var inputety = view.Contexts.input.CreateEntity(); inputety.AddInputNewPosition(view.ID, ScenePositionUtility.Instance.GetSpawnPosition(view.Entity.viewData.spawnPositionID)); } }
public virtual void EnterView(UnityView currentView) { gameObject.SetActive(true); foreach (Action <Dictionary <UnityViewOptions, object> > listener in Listeners) { listener(currentView?.Options); } }
/// <summary> /// Initializes a GameState to be used in a FSM. /// </summary> /// <param name="lobby">The lobby this gamestate belongs to.</param> public GameState(Lobby lobby, TimeSpan? stateTimeoutDuration = null, StateExit exit = null) : base(stateTimeoutDuration: stateTimeoutDuration, exit: exit) { Lobby = lobby; UnityView = new UnityView(lobby) { ScreenId = TVScreenId.NoUnityViewConfigured }; this.Entrance.AddExitListener(() => { // When we are leaving the entrance / entering this state. Tell our lobby to update the current gamestate to be this one. this.Lobby.TransitionCurrentGameState(this); }); }
public override void Tick(float time) { Entity foundation = new Entity(); PositionComponent posCom = new PositionComponent(); posCom.position = pos; foundation.AddComponent(posCom); foundation.AddComponent(building); UnityView.AddEntity(foundation); Debug.Log("BULDING: foundation update"); }
public static void CreateInputCollision(this Collider2D other, UnityView self, CollisionType state) { var otherEntity = other.GetComponentInChildren <UnityView>(); if (otherEntity == null) { otherEntity = other.GetComponentInParent <UnityView>(); } if (otherEntity != null) { var input = self.Contexts.input.CreateEntity(); input.AddInputCollision(self.ID, otherEntity.ID, state); } }
IEnumerator TransitionSceneCoroutine(float delay, TVScreenId?id, UnityView view) { yield return(new WaitForSeconds(delay)); AnimationManagerScript.Singleton.ResetAndStopAllAnimations(); EventSystem.Singleton.ResetDataStructures(); BlurController.Singleton.ResetMasks(); ChangeView(id, view, true); EventSystem.Singleton.PublishEvent(new GameEvent() { eventType = GameEvent.EventEnum.EnteredState }); }
/// <summary> /// Iterates through all "object" dictionaries and parses objects. /// </summary> /// <param name="view"></param> /// <returns></returns> public UnityView ParseJObjects(UnityView view) { foreach (UnityViewOptions key in view?.Options?.Keys?.ToList() ?? new List <UnityViewOptions>()) { switch (key) { case UnityViewOptions.BlurAnimate: view.Options[key] = ((JObject)view.Options[key]).ToObject <UnityField <float?> >(); break; default: break; } } if (view.UnityObjects?.Value != null) { List <UnityObject> unityObjects = new List <UnityObject>(); foreach (object obj in view.UnityObjects.Value) { JObject jObject = (JObject)obj; switch (jObject["Type"].ToObject <UnityObjectType>()) { case UnityObjectType.Image: unityObjects.Add(jObject.ToObject <UnityImage>()); break; case UnityObjectType.Slider: unityObjects.Add(jObject.ToObject <UnitySlider>()); break; case UnityObjectType.Text: unityObjects.Add(jObject.ToObject <UnityText>()); break; default: throw new NotImplementedException("Not implemented"); } } view.UnityObjects.Value = unityObjects.Cast <object>().ToList(); } if (view.UnityObjects?.StartValue != null || view.UnityObjects?.EndValue != null) { throw new NotImplementedException("not implemented"); } return(view); }
public HumanPlayer(UnityView view, InputDevice inputDevice, TopDownActionCamera camera) { this.view = view; this.inputDevice = inputDevice; actions = TopDownActions.CreateWithJoystickBindings(); actions.Device = inputDevice; GameObject cursorObject = new GameObject(); CameraFocus focus = cursorObject.AddComponent <CameraFocus> (); focus.weight = 1f; cursor = cursorObject.AddComponent <BuildCursor> (); this.camera = camera; camera.SetFocus(cursor.gameObject.GetComponent <CameraFocus>()); cursor.AssertControl(actions, this); SetState(ControlState.BUILDING_GAME); }
private void SetupWorld() { //TODO initialize the view first... int numPeople = 5; int mapSize = 50; int numFoods = 20; for (int i = 0; i < numFoods; ++i) { Vector2 pos = positionManager.closestEmpty(new Vector3(UnityEngine.Random.value * mapSize, 0f, UnityEngine.Random.value * mapSize)); if (PositionManager.IsBogus(pos)) { continue; } Entity food = new Entity(); PositionComponent position = new PositionComponent(); position.position = pos; food.AddComponent(position); foods.Add(position); PlantComponent plant = new PlantComponent(); food.AddComponent(plant); food.AddComponent(new CarriableComponent()); positionManager.ObjectSpawnedAt(food, pos); UnityView.AddEntity(food); } for (int i = 0; i < numPeople; ++i) { Vector2 pos = positionManager.closestEmpty(new Vector3(UnityEngine.Random.value * mapSize, 0f, UnityEngine.Random.value * mapSize)); if (PositionManager.IsBogus(pos)) { continue; } Entity person = new Entity(); PositionComponent position = new PositionComponent(); position.position = pos; person.AddComponent(position); HumanoidAI brain = new HumanoidAI(); person.AddComponent(brain); BehaviorComponent agent = new BehaviorComponent(brain); agent.name = GetRandomName(); person.AddComponent(agent); person.AddComponent(new InventoryComponent()); positionManager.ObjectSpawnedAt(person, pos); UnityView.AddEntity(person); UnityView.RegisterControllableAgent(person); } }
public static Entity CreatePlant(Vector2 position) { Vector3 offsetDir = UnityEngine.Random.onUnitSphere; var plantPos = new PositionComponent(); plantPos.position = position; var plantPlant = new PlantComponent(); Entity plant = new Entity(); plant.AddComponent(plantPos); plant.AddComponent(plantPlant); plant.AddComponent(new CarriableComponent()); ProceduralWorldSimulator.instance.positionManager.ObjectSpawnedAt(plant, position); ProceduralWorldSimulator.instance.foods.Add(plantPos); UnityView.AddEntity(plant); return(plant); }
public void Init() { EcsEntity cameraEntity = _world.NewEntity(); CameraComponent cameraComponent = cameraEntity.Set <CameraComponent>(); cameraComponent.MainCamera = Camera.main; Positioning.Components.Position position = cameraEntity.Set <Positioning.Components.Position>(); position.Point = cameraComponent.MainCamera.transform.position; position.EulerRotation = cameraComponent.MainCamera.transform.eulerAngles; UnityView unityView = cameraEntity.Set <UnityView>(); unityView.GameObject = cameraComponent.MainCamera.gameObject; unityView.Transform = cameraComponent.MainCamera.transform; _camPosition = position; }
public void SwitchToView(TVScreenId?id, UnityView view) { if (view != null && view.Id != lastGuid) { lastGuid = view.Id; EventSystem.Singleton.PublishEvent(new GameEvent() { eventType = GameEvent.EventEnum.ExitingState }); AnimationManagerScript.Singleton.SendAnimationWrapUp(0.6f); StartCoroutine(TransitionSceneCoroutine(0.6f, id, view)); } else { ChangeView(id, view); EventSystem.Singleton.PublishEvent(new GameEvent() { eventType = GameEvent.EventEnum.UserSubmitted }); } }
public void ChangeView(TVScreenId?id, UnityView view, bool newScene = false) { if (CurrentView.HasValue && AvailableTVViews.ContainsKey(CurrentView.Value)) { AvailableTVViews[CurrentView.Value].ExitView(); } else { DefaultView?.ExitView(); } if (id.HasValue && AvailableTVViews.ContainsKey(id.Value)) { AvailableTVViews[id.Value].EnterView(view); } else { DefaultView?.EnterView(null); } CurrentView = id; }
public RevealGameState( Lobby lobby, string promptTitle, UnityView revealUnityView) : base( lobby: lobby, exit: new WaitForPartyLeader_StateExit( lobby: lobby, partyLeaderPromptGenerator: Prompts.ShowScoreBreakdowns( lobby: lobby, promptTitle: promptTitle, userPromptId: UserPromptId.PartyLeader_SkipReveal, userScoreBreakdownScope: Score.Scope.Reveal, showPartyLeaderSkipButton: true), waitingPromptGenerator: Prompts.ShowScoreBreakdowns( lobby: lobby, promptTitle: promptTitle, userScoreBreakdownScope: Score.Scope.Reveal))) { this.Entrance.Transition(this.Exit); this.UnityView = revealUnityView; }
void Button_Clicked(System.Object sender, System.EventArgs e) { UnityView.UnitySendMessage("MyCanvas", "SetCubeColor", HexColorEntry.Text.Trim()); }
// Use this for initialization void Awake() { viewer = this; CreateMap(); }
/// <summary> /// Use this to lock unity on a custom view made in Test Client /// ==================================================================================== /// THIS CODE IS ONLY FOR DEBUGGING PURPOSES AND SHOULD NOT BE CALLED EVER ON PRODUCTION /// ==================================================================================== /// </summary> /// <param name="id"></param> /// <param name="view"></param> public void SetDebugCustomView(TVScreenId?id, UnityView view) { ChangeView(id, view); }
public void UpdateBuildControls() { if (following) { if (cursor != null && entity != null) { var homonid = UnityView.GetHomonid(entity); if (homonid != null) { cursor.transform.position = homonid.transform.position; } } if (actions.Move.Vector.magnitude > 1E-4) { following = false; UnityView.viewer.topDownActionCam.SetFocus(cursor.gameObject.GetComponent <CameraFocus>()); } } if (actions.Back.WasPressed) { SetState(ControlState.ACTION_GAME); } if (actions.SpeechUp.WasPressed) { SetState(ControlState.ACTION_GAME); } if (actions.SpeechLeft.WasPressed) { //previous entity, move to and lock on until the camera is panned } if (actions.SpeechRight.WasPressed) { //next entity, move to and lock on until the camera is panned } if (actions.Primary.WasPressed) { entity = UnityView.GetNextEntity(entity); //TODO fix this UnityView.FocusCameraOn(entity, camera); following = true; } if (actions.Secondary.WasPressed) { entity = UnityView.GetPrevEntity(entity); //TODO fix this UnityView.FocusCameraOn(entity, camera); following = true; } if (actions.TriggerAction) { TopDownActionCamera cam = UnityView.GetCamera(this); if (cam == null) { return; } cam.Zoom(1f / GetZoom()); } if (actions.LockOn) { TopDownActionCamera cam = UnityView.GetCamera(this); if (cam == null) { return; } cam.Zoom(GetZoom()); } }
private void Awake() { _listener = GetComponent <UnityView>(); }