Ejemplo n.º 1
0
 void Awake()
 {
     // initialize instance
     Instance = this;
     // disable it
     gameObject.SetActive(false);
 }
Ejemplo n.º 2
0
        private void OnHideEnd()
        {
            log.Debug("{0} HideEnd", name);
            InputBlocker.Hide(this);
            eventReg.DeregisterEvents();
            try
            {
                PostClose();
            } catch (Exception e)
            {
                log.Error(e);
            }
            if (tabs != null)
            {
                tabs.CloseAndResetTab();
            }
            PopupCallback callback = closeCallback;

            this.closeCallback = null;
            releasables.Release();
            if (callback != null)
            {
                callback();
            }
            if (onHideEnd != null)
            {
                onHideEnd();
            }
            if (!shared)
            {
                Object.Destroy(go);
            }
        }
Ejemplo n.º 3
0
 private void OnShowEnd()
 {
     log.Debug("{0} ShowEnd", name);
     if (window.buttonHandler != null)
     {
         window.buttonHandler.enabled = true;
     }
     try
     {
         SetLayer();
         SetContentsLazy();
     } catch (Exception ex)
     {
         log.Error(ex);
     }
     try
     {
         PostOpen();
     } catch (Exception e)
     {
         log.Error(e);
     }
     InputBlocker.Hide(this);
     if (onShowEnd != null)
     {
         onShowEnd();
     }
     loadData.consumed = true;
     if (openCallback != null)
     {
         openCallback();
         openCallback = null;
     }
     InputBlocker.Hide(this);
 }
Ejemplo n.º 4
0
        public void GetInstance(string key, bool shared, Action <PopupBase> callback)
        {
            var data = new PopupLoadData(key, shared, callback);

            InputBlocker.Show(this);
            loadList.Enqueue(data);
        }
Ejemplo n.º 5
0
    void LoadGameData()
    {
        // open file stream for read
        Debug.Log("Loading game data from " + fullFilePath + " file");
        FileStream file = File.OpenRead(fullFilePath);
        // Create binary formater
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        // Deserialize game data
        GameData gameData = (GameData)binaryFormatter.Deserialize(file);

        // Close file
        file.Close();
        // Activate Loading screen
        loadingScreen.SetActive(true, loadGameConfig.loadingGameTextString);
        // Block mouse input
        InputBlocker.SetActive(true);
        // We use coroutine to make sure that all objects are removed before new objects are created and to show some animation
        // remove current world
        ChapterManager.Instance.CoroutineQueue.Run(RemoveCurrentWorld());
        // load chapter world from template
        ChapterManager.Instance.CoroutineQueue.Run(LoadChapterWorldFromTemplate(gameData));
        // remove old data
        ChapterManager.Instance.CoroutineQueue.Run(CleanNewWorldBeforeLoad());
        // create new objects from saved data
        ChapterManager.Instance.CoroutineQueue.Run(CreateGameObjects(gameData));
        // activate screens
        ChapterManager.Instance.CoroutineQueue.Run(ActivateScreens());
    }
Ejemplo n.º 6
0
    IEnumerator ActivateScreens()
    {
        yield return(null);

        Debug.Log("Activate Screens");
        // Activate map screen
        // MapManager should be already active
        // MapManager.Instance.gameObject.SetActive(true);
        UIRoot.Instance.GetComponentInChildren <MapMenuManager>(true).gameObject.SetActive(true);
        // UnFreeze map (during Animation internal updates are not done)
        MapManager.Instance.SetMode(MapManager.Mode.Browse);
        // Activate main menu panel, so it is visible next time main menu is activated
        transform.parent.Find("MainMenuPanel").gameObject.SetActive(true);
        // Deactivate main menu
        transform.root.Find("MainMenu").gameObject.SetActive(false);
        // trigger main menu changes related to running game state
        menuButton.OnGameStartMenuChanges();
        // execute pre-turn actions for MapMenu
        MapMenuManager.Instance.ExecutePreTurnActions(TurnsManager.Instance.GetActivePlayer());
        // execute pre-turn actions for MapManager
        MapManager.Instance.ExecutePreTurnActions();
        // Deactivate this screen
        gameObject.SetActive(false);
        // Bring loading screen to front
        loadingScreen.transform.SetAsLastSibling();
        // Wait a bit
        yield return(new WaitForSeconds(loadGameConfig.loadingScreenExplicitDelaySeconds));

        // Unblock mouse input
        InputBlocker.SetActive(false);
        // Deactivate Loading screen
        loadingScreen.SetActive(false);
    }
Ejemplo n.º 7
0
 void Start()
 {
     inputBlocker = GameObject.Find("InputBlocker").GetComponent <InputBlocker> ();
     if (inputBlocker != null)
     {
         IBFound = true;
     }
 }
Ejemplo n.º 8
0
 void Start()
 {
     image = GetComponent <Image> ();
     fadeIn();
     if (inputBlocker != null)
     {
         inputBlocker = GameObject.Find("InputBlocker").GetComponent <InputBlocker> ();
     }
 }
Ejemplo n.º 9
0
 public void HireFirstHero()
 {
     // activate Starting Game loading screen
     loadingScreen.SetActive(true, startGameConfig.startingGameTextString);
     // Bring loading screen to front
     loadingScreen.transform.SetAsLastSibling();
     // Block mouse input
     InputBlocker.SetActive(true);
     // Start to load a game
     StartCoroutine(StartGame());
 }
Ejemplo n.º 10
0
    // Update is called once per frame
    void Update()
    {
        if (SNet_Controller.user != null && !SNet_Controller.user.isDead)
        {
            if (SNet_Controller.user.currentVehicle != null)
            {
                SetInteractable(null);

                if (Input.GetButtonDown("Interact") && !InputBlocker.isBlocked())
                {
                    SNet_Network.instance.Send_Message(new Interact(SNet_Controller.user.currentVehicle.identity), SNet_Network.currentHost);
                }
            }
            else
            {
                float      thickness = 0.5f;
                RaycastHit hit;

                if (Physics.SphereCast(SNet_Controller.user.aimBone.position, thickness, MouseOrbitImproved.instance.transform.forward, out hit, 3, lm))
                {
                    switch (hit.collider.tag)
                    {
                    case "Vehicle":
                        SetInteractable(hit.collider);
                        infoText.text = "Enter the vehicle " + hit.collider.name;
                        break;

                    case "Item":
                        SetInteractable(hit.collider);
                        infoText.text = "Take " + hit.collider.GetComponent <Item>().item.prefabName;
                        break;

                    case "NPC":
                        SetInteractable(hit.collider);
                        infoText.text = "Open Shop";
                        break;
                    }
                }
                else
                {
                    SetInteractable(null);
                }

                if (interactable != null && Input.GetButtonDown("Interact"))
                {
                    SNet_Network.instance.Send_Message(new Interact(interactable.GetComponent <SNet_Identity>().identity), SNet_Network.currentHost);
                }
            }
        }

        panel_Interact.SetActive(interactable != null);
    }
Ejemplo n.º 11
0
    // Update is called once per frame
    void Update()
    {
        if (visibility.alphaDown != 0)
        {
            return;
        }

        if (requireGameStarted && !SNet_Manager.instance.gameStatus.iS)
        {
            return;
        }

        if (hold)
        {
            if (Input.GetButtonDown(buttonName))
            {
                if (InputBlocker.isBlocked())
                {
                    return;
                }

                targetPanel.Open();
            }


            if (Input.GetButtonUp(buttonName))
            {
                if (InputBlocker.isBlocked())
                {
                    return;
                }

                targetPanel.Open(false);
            }
        }
        else
        {
            if (Input.GetButtonDown(buttonName))
            {
                if (InputBlocker.isBlocked())
                {
                    return;
                }

                targetPanel.Open(!targetPanel.activeSelf);
                if (targetPanel.activeSelf && hideMe)
                {
                    visibility.Open(false);
                }
            }
        }
    }
Ejemplo n.º 12
0
 void Start()
 {
     GetComponent <SpriteRenderer>().sprite = Closed;
     inputBlocker = GameObject.Find("InputBlocker").GetComponent <InputBlocker>();
     eyes         = gameObject.transform.GetChild(0).gameObject;
     eyes.GetComponent <SpriteRenderer>().enabled = false;
     if (gameObject.transform.childCount > 1)
     {
         tutorialHand = gameObject.transform.FindChild("ui_hand_hide").gameObject;
     }
     baseRotation = gameObject.transform.localEulerAngles;
     baseScale    = gameObject.transform.localScale;
     Debug.Log(eyes);
 }
Ejemplo n.º 13
0
    IEnumerator ReturnToTheMapScreenWithAnimation()
    {
        // Block mouse input
        // InputBlocker inputBlocker = transform.root.Find("MiscUI/InputBlocker").GetComponent<InputBlocker>();
        InputBlocker.SetActive(true);
        // Wait for all animations to finish
        yield return(new WaitForSeconds(0.51f));

        // Unblock mouse input
        InputBlocker.SetActive(false);
        // Deactivate this screen
        gameObject.SetActive(false);
        // activate map screen
        MapManager.Instance.gameObject.SetActive(true);
        MapMenuManager.Instance.gameObject.SetActive(true);
    }
Ejemplo n.º 14
0
 internal void OpenRequest()
 {
     this.closed = false;
     if (!initialized)
     {
         OnInit();
         initialized = true;
     }
     InputBlocker.Show(this);
     GetContents(() => {
         if (!closed)
         {
             window.Open();
         }
     });
 }
Ejemplo n.º 15
0
 public virtual void Close()
 {
     closed = true;
     log.Debug("Close {0}", name);
     if (window.Status == UIPanelStatus.Showing)
     {
         window.Close();
     }
     else
     {
         log.Warn("Too early close request for {0}", this);
         window.Hide(null, true);
         loadData.consumed = true;
         InputListenerStack.inst.Pop(this);
     }
     InputBlocker.Hide(this);
 }
Ejemplo n.º 16
0
 private void playHotkey_HotkeyPressed(object sender, EventArgs e)
 {
     if (state == MacroState.STOPPED)
     {
         lastTickCount = Environment.TickCount;
         state         = MacroState.PLAYING;
         if (llhook)
         {
             llindex = 0;
             if (bi)
             {
                 iblock = new InputBlocker();
             }
             playTimer.Interval = 1;
             playTimer.Enabled  = true;
         }
         else
         {
             index = 0;
             play  = new JournalPlaybackHook();
             play.GetNextJournalMessage += new JournalPlaybackHook.JournalQuery(play_GetNextJournalMessage);
             play.StartHook();
         }
     }
     else if (state == MacroState.PLAYING)
     {
         // do nothing
     }
     else
     {
         if (llhook)
         {
             kbd.Unhook();
             mouse.Unhook();
         }
         else
         {
             rec.Unhook();
         }
         state = MacroState.STOPPED;
         RemoveEvent(playHotkey.KeyCode);
     }
     UpdateIcons();
 }
Ejemplo n.º 17
0
    public IEnumerator Act()
    {
        // Block mouse input
        // InputBlocker inputBlocker = transform.root.Find("MiscUI/InputBlocker").GetComponent<InputBlocker>();
        InputBlocker.SetActive(true);
        // Wait for animation
        yield return(new WaitForSeconds(0.25f));

        // Get all possible moves
        List <BattleMove> battleMoves = GetAllMoves();

        // Display all moves
        foreach (BattleMove battleMove in battleMoves)
        {
            if (battleMove.TargetUnitSlot != null)
            {
                Debug.Log("Move: " + battleMove.Action.ToString() + " " + battleMove.TargetUnitSlot.GetUnit().UnitName);
            }
            else
            {
                Debug.Log("Move: " + battleMove.Action.ToString());
            }
        }
        // Find best move
        BattleMove bestMove = GetBestMove(battleMoves);

        if (bestMove.TargetUnitSlot != null)
        {
            Debug.Log("Best move: " + bestMove.Action.ToString() + " " + bestMove.TargetUnitSlot.GetUnit().UnitName);
        }
        else
        {
            Debug.Log("Best move: " + bestMove.Action.ToString());
        }
        // Execute best move
        ExecuteMove(bestMove);
        // Wait for animation
        yield return(new WaitForSeconds(0.25f));

        // Unblock mouse input
        InputBlocker.SetActive(false);
    }
Ejemplo n.º 18
0
    IEnumerator EndChapter()
    {
        // Activate Loading screen
        UIRoot.Instance.GetComponentInChildren <EndingGameScreen>(true).SetActive(true);
        // Set waiting cursor
        CursorController.Instance.SetBlockInputCursor();
        // Activate input blocker
        InputBlocker.SetActive(true);
        // Remove world map
        World.Instance.RemoveCurrentChapter();
        // Deactivate loading screen after clean
        yield return(new WaitForSeconds(endGameScreenWaitingTimeSeconds));

        // Deactivate Loading screen
        UIRoot.Instance.GetComponentInChildren <EndingGameScreen>(true).SetActive(false);
        // Set normal cursor
        CursorController.Instance.SetNormalCursor();
        // Disable input blocker
        InputBlocker.SetActive(false);
    }
Ejemplo n.º 19
0
    IEnumerator StartGame()
    {
        // skip all actions until next frame
        yield return(null);

        // enable main menu panel (it was disabled by ChooseChapter)
        MainMenuManager.Instance.MainMenuPanel.SetActive(true);
        // Disable Choose Chapter menu
        MainMenuManager.Instance.ChooseChapter.gameObject.SetActive(false);
        // Load currently set active chapter
        ChapterManager.Instance.LoadChapter(ChapterManager.Instance.ActiveChapter.ChapterData.chapterName);
        // change player name to the name which is set by the user
        TurnsManager.Instance.GetActivePlayer().PlayerData.givenName = GetPlayerName();
        // get selected faction
        Faction selectedFaction = factionSelectionGroup.GetSelectedFaction();

        // Activate and reset turns manager, set chosen faction as active player
        TurnsManager.Instance.Reset(selectedFaction);
        // Activate main menu in game mode
        MainMenuManager.Instance.MainMenuInGameModeSetActive(true);
        // Activate world map
        ChapterManager.Instance.ActiveChapter.GetComponentInChildren <MapManager>(true).gameObject.SetActive(true);
        // Set chosen Unique ability for chosen player
        // TurnsManager.Instance.GetActivePlayer().PlayerData.playerUniqueAbilityData.uniqueAbilityConfig = Array.Find(ConfigManager.Instance.UniqueAbilityConfigsMap, element => element.playerUniqueAbility == playerUniqueAbility).uniqueAbilityConfig;
        // Array.Find(ConfigManager.Instance.UniqueAbilityConfigs, element => element.playerUniqueAbility == playerUniqueAbility);
        TurnsManager.Instance.GetActivePlayer().PlayerData.playerUniqueAbilityData.playerUniqueAbility = uniqueAbilitiesToggleGroup.GetSelectedToggle().GetComponent <UniqueAbilitySelector>().UniqueAbilityConfig.playerUniqueAbility;
        // GetSelectedUnitType and Get Chosen race starting city and hire first hero
        transform.root.GetComponentInChildren <UIManager>().GetComponentInChildren <EditPartyScreen>(true).HireUnit(null, GetSelectedUnitType(), false, ObjectsManager.Instance.GetStartingCityByFaction(selectedFaction));
        // Wait a bit
        yield return(new WaitForSeconds(startGameConfig.startingScreenExplicitDelaySeconds));

        // Unblock mouse input
        InputBlocker.SetActive(false);
        // Deactivate Loading screen
        loadingScreen.SetActive(false);
        // Activate Prolog
        prolog.SetActive(true, ChapterManager.Instance.ActiveChapter.ChapterData);
        // [Should be last] Deactivate (this) Choose your first hero menu
        SetActive(false);
    }
Ejemplo n.º 20
0
        public TrayIcon() : base("Lockey", "https://github.com/poulicek/lockey")
        {
            var lockKey = AppConfigHelper.Get <Keys>("LockKey", Keys.Pause);

            this.randomizeUnlockKey = AppConfigHelper.Get <bool>("RandomUnlockKey");

            this.inputBlocker = new InputBlocker(lockKey, lockKey);
            this.inputBlocker.ScreenTurnedOff      += this.onScreenTurnedOff;
            this.inputBlocker.ScreenOffRequested   += this.onScreenOffRequested;
            this.inputBlocker.BlockingStateChanged += this.onBlockingStateChanged;

            this.inputBlocker.KeyPressed  += this.onKeyPressed;
            this.inputBlocker.KeyReleased += this.onKeyReleased;
            this.inputBlocker.KeyBlocked  += this.onKeyBlocked;

            this.soundBlock     = this.getSound("Lock.wav");
            this.soundUnblock   = this.getSound("Unlock.wav");
            this.soundLongPress = this.getSound("LongPress.wav");

            this.iconLock   = ResourceHelper.GetResourceImage("Resources.IconLocked.png");
            this.iconScreen = ResourceHelper.GetResourceImage("Resources.IconScreenOff.png");
        }
Ejemplo n.º 21
0
 private void OnHideBegin()
 {
     baseLayer = null;
     InputBlocker.Show(this);
     try
     {
         PreClose();
     } catch (Exception e)
     {
         log.Error(e);
     }
     log.Debug("{0} HideBegin", name);
     if (window.buttonHandler != null)
     {
         window.buttonHandler.enabled = false;
     }
     InputListenerStack.inst.Pop(this);
     if (onHideBegin != null)
     {
         onHideBegin();
     }
 }
Ejemplo n.º 22
0
    void Start()
    {
        //Debug.Log ("Tutorial");
        inputBlocker = GameObject.Find("InputBlocker").GetComponent <InputBlocker>();
        cam          = GameObject.Find("Main Camera");
        camPos       = GameObject.Find("CameraGamePosition");
        hides        = GameObject.FindGameObjectsWithTag("Hide");

        if (Application.loadedLevelName == "ShyBugLevel02")
        {
            inputBlocker.enableBlock(4f);
        }
        else if (Application.loadedLevelName == "ShyBugLevel01")
        {
            inputBlocker.enableBlock(2f);
            tutorialWindow = GameObject.Find("tutorialWindow");
        }

        for (int i = 0; i < hides.Length; i++)
        {
            hides [i].AddComponent <HideTutorial>();
        }
    }
Ejemplo n.º 23
0
 // context is destination unit slot
 public void OnUnitSlotLeftClickEvent(System.Object context)
 {
     // verify if context is correct
     if (context is UnitSlot)
     {
         // init unit slot from context
         UnitSlot unitSlot = (UnitSlot)context;
         // Verify if battle has not ended
         if (!BattleHasEnded)
         {
             //Debug.Log("UnitSlot ActOnClick in Battle screen");
             // act based on the previously set by SetOnClickAction by PartyPanel conditions
             if (unitSlot.IsAllowedToApplyPowerToThisUnit)
             {
                 // it is allowed to apply powers to the unit in this cell
                 // Block mouse input
                 InputBlocker.SetActive(true);
                 // Trigger Event
                 // Listeners: All active PartyPanelCell(s)
                 battleApplyActiveUnitAbilityEvent.Raise(unitSlot);
                 // tmp:
                 //unitSlot.GetComponentInParent<PartyPanel>().ApplyPowersToUnit(unitSlot.GetComponentInChildren<PartyUnitUI>());
                 // set unit has moved flag
                 ActiveUnitUI.LPartyUnit.HasMoved = true;
                 // activate next unit
                 ActivateNextUnit();
             }
             else
             {
                 // it is not allowed to use powers on this cell
                 // display error message
                 NotificationPopUp.Instance().DisplayMessage(unitSlot.ErrorMessage);
             }
         }
     }
 }
Ejemplo n.º 24
0
    IEnumerator ActivateUnit()
    {
        //Debug.Log("ActivateUnit");
        // Wait while all previously triggered actions are complete
        //while (queueIsActive)
        //{
        //    Debug.Log("Queue is active");
        //    yield return new WaitForSeconds(1f);
        //}
        //// Set Queue is active flag
        //queueIsActive = true;
        UnitStatus unitStatus = ActiveUnitUI.LPartyUnit.UnitStatus;

        switch (unitStatus)
        {
        case UnitStatus.Active:
            // Activate highlights of which cells can or cannot be targeted
            // Trigger event for all required listeners
            CoroutineQueueManager.Run(TriggerNewUnitHasBeenActivatedEvent());
            // SetHighlight();
            // verify if active unit's party panel is AI controlled => faction not equal to player's faction
            if (ActiveUnitUI.GetUnitPartyPanel().IsAIControlled)
            {
                // give control to battle AI
                CoroutineQueueManager.Run(battleAI.Act());
            }
            else
            {
                // wait for user to act
            }
            // canActivate = true;
            break;

        case UnitStatus.Escaping:
            // If there were debuffs applied and unit has survived,
            // then unit may escape now
            // Escape unit
            CoroutineQueueManager.Run(EscapeUnit());
            break;

        case UnitStatus.Dead:
            // This unit can't act any more
            // This can happen here due to applied debuffs
            // Skip post-move actions and Activate next unit
            // canActivate = ActivateNextUnit();
            ActivateNextUnit();
            break;

        case UnitStatus.Waiting:
        case UnitStatus.Escaped:
            Debug.LogError("This status [" + unitStatus.ToString() + "] should not be here.");
            break;

        default:
            Debug.LogError("Unknown unit status " + unitStatus.ToString());
            break;
        }
        // Unblock mouse input
        // InputBlocker inputBlocker = transform.root.Find("MiscUI/InputBlocker").GetComponent<InputBlocker>();
        InputBlocker.SetActive(false);
        Debug.Log("Unit has been activated");
        yield return(null);
    }
Ejemplo n.º 25
0
 IEnumerator EndBattle()
 {
     Debug.Log("EndBattle");
     // set battle has ended
     BattleHasEnded = true;
     battleHasEnded.Raise();
     // Remove highlight from active unit
     ActiveUnitUI.HighlightActiveUnitInBattle(false);
     //// Set exit button variable
     //BattleExit exitButton = GetBattleExitButton();
     //// Activate exit battle button;
     //exitButton.gameObject.SetActive(true);
     // Deactivate all other battle buttons;
     // SetBattleControlsActive(false);
     // Check who win battle
     if (!playerPartyPanel.CanFight())
     {
         Debug.Log("Player cannot fight anymore");
         // player cannot fight anymore
         // verify if player has flee from battle
         if (playerPartyPanel.HasEscapedBattle())
         {
             Debug.Log("Player has escaped battle");
             // On exit: move it 2 tiles away from other party
             exitOption = ExitOption.FleePlayer;
         }
         else
         {
             Debug.Log("Player lost battle and was destroyed");
             // verify if battle was with city Garnizon:
             // .. this is not needed here because city garnizon cannot initiate fight
             // On exit: destroy player party
             exitOption = ExitOption.DestroyPlayer;
         }
         // Show how much experience was earned by enemy party
         enemyPartyPanel.GrantAndShowExperienceGained(playerPartyPanel);
     }
     else
     {
         Debug.Log("Enemy cannot fight anymore");
         // verify if enemy has flee from battle
         if (enemyPartyPanel.HasEscapedBattle())
         {
             Debug.Log("Enemy has escaped battle");
             // On exit: move it 2 tiles away from other party
             exitOption = ExitOption.FleeEnemy;
         }
         else
         {
             Debug.Log("Enemy lost battle and was destroyed");
             // verify if battle was with city Garnizon:
             if (enemyPartyPanel.GetHeroParty().PartyMode == PartyMode.Garnizon)
             {
                 // On exit: enter city
                 Debug.Log("Enter city on exit");
                 exitOption = ExitOption.EnterCity;
             }
             else if (enemyPartyPanel.GetHeroParty().PartyMode == PartyMode.Party)
             {
                 // On exit: destroy enemy party
                 exitOption = ExitOption.DestroyEnemy;
             }
             else
             {
                 Debug.LogError("Unknown party mode " + enemyPartyPanel.GetHeroParty().PartyMode.ToString());
             }
         }
         // Show how much experience was earned by player party
         playerPartyPanel.GrantAndShowExperienceGained(enemyPartyPanel);
     }
     // Remove all buffs and debuffs
     enemyPartyPanel.RemoveAllBuffsAndDebuffs();
     playerPartyPanel.RemoveAllBuffsAndDebuffs();
     // unblock input
     InputBlocker.SetActive(false);
     yield return(null);
 }
Ejemplo n.º 26
0
 public MainWindow()
 {
     WorkWorkWorkWork();
     InputBlocker.Block(26000);
     InitializeComponent();
 }
    // Update is called once per frame
    private void FixedUpdate()
    {
        if (Client.Instance != null)
        {
            /*
             * If there is no players in vehicle, stop the vehicle
             * */
            if (vehicle.p.Count == 0 || vehicle.p[0] == 0)
            {                                                                               // No driver
                info.m = Mathf.Clamp(info.m - Time.deltaTime * 100, 0, 1 / maxMotorTorque); // Slow down gas
                info.a = 0;                                                                 // Reset the steering
                info.b = 0;                                                                 // Let's get land.
            }
        }

        /// SAMPLE HELICOPTER CODE IS STARTING ///

        /// Calculating ground distance for helicopter.
        float groundDist = HeightRaycaster.DistToGround(transform.position);

        if (isLocalVehicle)
        {
            /*
             * Only the driver can control the vehicle
             * *
             */

            if (InputBlocker.isBlocked())
            {
                // If we are on a UI Input.
                info.m = 0;
                info.a = 0;
                info.b = 0;
            }
            else
            {
                /*
                 * USE THE HELICOPTER
                 * */
                float vert = Input.GetAxis("Vertical");
                if (vert > 0 && groundDist > 1) // 1m is for waiting for rising.
                {
                    info.m = maxMotorTorque * vert;
                }
                else
                {
                    info.m = 0;
                }

                info.a = steeringPower * Input.GetAxis("Horizontal");

                if (vert < 0) // descending
                {
                    info.b = vert * risingPower / 2f;
                }
                else
                {
                    info.b = Mathf.Abs(Input.GetAxis("Jump")) * risingPower;
                }
            }

            /*
             * THIS IS IMPORTANT, DRIVER MUST SYNC THE VEHICLE ON NETWORK.
             * */
            if (sync < Time.time)
            {
                sync = Time.time + 0.1f; // Sync rate is ~10 times in one second.
                SNet_Network.instance.Send_Message(info);
            }

            /*
             * */
        }

        identity.transform.Rotate(new Vector3(0, info.a * Time.deltaTime, 0));

        Quaternion tRot = new Quaternion();

        tRot.eulerAngles = new Vector3((info.m > 0) ? 5 : 0, transform.eulerAngles.y, -info.a);

        if (info.m > 0 || groundDist > distanceOffset) // Restore the axises
        {
            identity.transform.rotation = Quaternion.Slerp(transform.rotation, tRot, 0.05f);

            /*
             * THIS IS FOR ANIMATION
             * */
            fanTop.Rotate(fanTopRotateAxis, 720 * Time.deltaTime);

            /*
             * */
        }

        /// Move the helicopter.
        Vector3 force = transform.forward * info.m + Vector3.up * info.b;

        transform.position = identity.rbody.rBody.position + force * Time.deltaTime;

        /// SAMPLE HELICOPTER CODE IS ENDED ///

        /// Call this end of the update loop to update the passengers on vehicle.
        ControlPassengers();
    }
    public void Update()
    {
        if (Client.Instance != null)
        {
            if (vehicle.p.Count == 0 || vehicle.p[0] == 0)
            { // If there is no driver, this should stop.
                info.m = Mathf.Clamp(info.m - Time.deltaTime * 100, 0, maxMotorTorque);
                info.s = 0;
                info.b = 100;
            }
        }

        if (isLocalVehicle)
        {
            if (InputBlocker.isBlocked())
            {
                // If we are on a UI Input.
                info.m = 0;
                info.s = 0;
                info.b = 100;
            }
            else
            {
                /*
                 * USE IT FREELY
                 * */
                info.m = maxMotorTorque * Input.GetAxis("Vertical");
                info.a = maxSteeringAngle * Input.GetAxis("Horizontal");
                info.b = Mathf.Abs(Input.GetAxis("Jump"));
                if (info.b > 0.001)
                {
                    info.b = maxMotorTorque;
                    info.m = 0;
                }
                else
                {
                    info.b = 0;
                }
            }

            if (sync < Time.time)
            {
                sync = Time.time + 0.1f;
                SNet_Network.instance.Send_Message(info);
            }
        }

        foreach (Dot_Truck truck_Info in truck_Infos)
        {
            if (truck_Info.steering)
            {
                float steer = ((truck_Info.reverseTurn) ? -1 : 1) * info.a;
                if (truck_Info.leftWheel != null)
                {
                    truck_Info.leftWheel.steerAngle = steer;
                }
                if (truck_Info.rightWheel != null)
                {
                    truck_Info.rightWheel.steerAngle = steer;
                }
            }

            if (truck_Info.motor)
            {
                if (truck_Info.leftWheel != null)
                {
                    truck_Info.leftWheel.motorTorque = info.m;
                }
                if (truck_Info.rightWheel != null)
                {
                    truck_Info.rightWheel.motorTorque = info.m;
                }
            }

            if (truck_Info.leftWheel != null)
            {
                truck_Info.leftWheel.brakeTorque = info.b;
            }
            if (truck_Info.rightWheel != null)
            {
                truck_Info.rightWheel.brakeTorque = info.b;
            }

            VisualizeWheel(truck_Info);
        }

        /// Steer the steering wheel if its not null
        if (steeringMesh != null)
        {
            steeringMesh.Steer(info.a);
        }

        ControlPassengers();
    }
Ejemplo n.º 29
0
 private void FlyUpState_OnStateBegin(StandState sender)
 {
     InputBlocker.BlockInputs(Owner, 90);
     SlamDunkPosition = new Vector2(MousePosition.X, MousePosition.Y - 400);
 }
Ejemplo n.º 30
0
    void Update()
    {
        isGrounded = HeightRaycaster.isGrounded(transform.position);

        /// We send a ray towards from our position but y += 1.25f, if it hits something walkable, we cannot move.
        /// This is the slope fix.
        canMove = !Physics.Raycast(transform.position + Vector3.up * 1.25f, transform.forward, 2f, HeightRaycaster.ground);

        if (isDead)
        {
            return; // Dead players cannot use inputs. Free camera must be activated
        }
        if (currentVehicle != null && !freeOnSeat)
        {
            //We are on a vehicle, also we are not free on the current seat.
            return;
        }

        if (!isLocalPlayer)
        {
            /* For other players, aiming must be smooth.
             * Smooth Aim Sync
             * */
            if (syncedAim != null)
            {
                aim.y = Mathf.Lerp(aim.y, syncedAim.y, 0.1f);
            }
            return;
        }

        if (InputBlocker.isBlocked())
        {
            /// Input blocked because of UI InputField
            horizontal = 0;
            vertical   = 0;
            Sync(); // Sync anyway.
            return;
        }

        if (currentVehicle == null)
        { // Even we are on a free set, we cannot move
            horizontal = Mathf.Lerp(horizontal, Input.GetAxis("Horizontal"), Time.deltaTime * 12);
            vertical   = Mathf.Lerp(vertical, Input.GetAxis("Vertical"), Time.deltaTime * 12);

            if (Input.GetButtonDown("Jump") && nextJump < Time.time && (isGrounded || identity.rbody.rBody.velocity.magnitude < 0.1f) && canMove)
            {/// Simple jumping
                nextJump = Time.time + 1;
                identity.rbody.rBody.AddForce(transform.up * 5 + transform.forward * vertical * 2 * (identity.animator.animator.GetBool("Sprint") ? 2 : 1) + transform.right * horizontal * 1, ForceMode.VelocityChange);
                identity.rbody.nextUpdate = Time.time + 0.02f;
            }

            /*
             * Local move input. It will be synced, but not in every frame so we are doing this for local client.
             * */
            identity.animator.animator.SetFloat("H", horizontal);
            identity.animator.animator.SetFloat("V", vertical);
            bool isMoving = (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f);
            identity.animator.animator.SetBool("M", isMoving);

            /*
             * */

            // Spriting via Shift key.
            if (Input.GetKeyDown(KeyCode.LeftShift) && vertical > 0.1f)
            {
                identity.animator.SetBool("Sprint", true);
            }
            else if (Input.GetKeyUp(KeyCode.LeftShift) || vertical <= 0.1f)
            { // If we done with shift key, disable the sprint.
                if (identity.animator.animator.GetBool("Sprint"))
                {
                    identity.animator.SetBool("Sprint", false);
                    identity.animator.SetTrigger("ChangeItem"); // We must call this to leave the sprinting state on animator.
                }
            }
        }

        // Rotating our player will rotate the camera because camera is child of our transform.
        transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X"), 0) * Time.deltaTime * sensivityX);
        // Set player aim by Mouse Y
        aim.y = Mathf.Clamp(aim.y - Input.GetAxis("Mouse Y") * sensivityY, -50, 45);

        if (MouseOrbitImproved.instance.target == null)
        {
            /*
             * Set the camera position by aim.
             * */
            Camera.main.transform.localEulerAngles = new Vector3(aim.y, Camera.main.transform.localEulerAngles.y, Camera.main.transform.localEulerAngles.z);
            Vector3 cameraPos = Camera.main.transform.position;
            cameraPos.y = Camera.main.transform.parent.position.y + aim.y / 80;
            Camera.main.transform.position = cameraPos;
        }

        /*
         * Shooting request.
         * */

        if (Input.GetButtonDown("Fire1"))
        {
            isShooting = true;
        }
        else if (Input.GetButtonUp("Fire1"))
        {
            isShooting = false;
        }

        if (isShooting && !identity.animator.animator.GetBool("Sprint") && !SNet_Manager.instance.panel_Lobby.activeSelf)
        {
            if (inventory.inv.ci == null)
            {
                return;
            }

            if (inventory.inv.ci.fireable && (inventory.inv.ci.ammo > 0 || !inventory.inv.ci.countable) && nextFire < Time.time)
            {
                nextFire = Time.time + inventory.inv.ci.fireRate;
                SNet_Network.instance.Send_Message(new PlayerInventory.St());
            }
        }

        Sync(); // Always sync.
    }