V
V
vodimak2022-02-18 18:21:25
C++ / C#
vodimak, 2022-02-18 18:21:25

How to disable player movement?

In short, when I pause the game, the player can fly (if it needs to fly in the game) and I don’t even understand why. help block movement on pause.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;

    public GameObject pauseMenuUI;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }

    public void Resume()
    {
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

    void Pause()
    {
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }

    public void LoadMenu()
    {
        Debug.Log("Load");
        Time.timeScale = 1f;
        SceneManager.LoadScene("menu");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Boronnikov, 2022-02-18
@red-cat-fat

Look, the best option is to encapsulate the control. In particular, create a class that will listen to the control from Input.GetKeyDown and store the movement vector in itself, for example.
Like make an IInputService interface that has a Vector3 GetMoveDirection() method - implementations of this method will take Input.GetKey(*W/A/S/D*) (or mobile control) and determine where to move.
And in order to block / unblock the player's movement - implement IInputService.Lock / IInputService.UnLock in which control will be "locked" through the IsLock variable. And already in each specific implementation, check whether the control is blocked.
Something like:

public Vector3 GetMoveDirection()
{
  if(IsLock){
    return Vector3.zero;
  }
  //а тут уже реализовать логику определения движения персонажа
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question