【问题标题】:Unity2D how to limit player jumpUnity2D如何限制玩家跳跃
【发布时间】:2020-06-21 00:35:58
【问题描述】:

所以我正在制作一个点击游戏,这是我的代码。我想问的是如何限制按钮点击,所以它不能被多次点击,因为如果我多次点击它,速度就会变得太快

public float downForce;
public float speed;

public int playerHp;

public Text healthText;

Rigidbody2D rb;

CharacterController controller;

void Awake()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    healthText.text = playerHp.ToString();
    if (Input.GetMouseButtonDown(0))
    {
        Jump();
    }

    if (playerHp < 0)
    {
        Destroy(this.gameObject);
        SceneManager.LoadScene("GameOver");
    }
}

public void Jump()
{
    rb.AddForce(Vector2.up * downForce + Vector2.right * speed, ForceMode2D.Impulse);
    rb.isKinematic = false;
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:
    public Button BTN;
    public float btnDelay = .5f;
    

    获取按钮引用并指定持续时间

    coroutine = ButtonDelayed(btnDelay);
    StartCoroutine(coroutine);
    

    在您在更新或Jump() 中调用Jump(); 之后

    IEnumerator ButtonDelayed(float delay)
    {
    BTN.interactable = false;
    yield return new WaitForSeconds(delay);
    BTN.interactable = !BTN.interactable;
    }
    

    这个地方。 只是一个快速的模型。不知道你是否会得到一个例外。如果您有问题,请联系我。

    编辑:我忘了告诉您将检查器中禁用状态的颜色更改为按钮可交互时的颜色。否则你会看到 Button 改变颜色。

    EDIT2:完整脚本已更新

    public float downForce;
    public float speed;   
    public int playerHp;   
    public Text healthText;
    
    Rigidbody2D rb;    
    CharacterController controller;
    
    public Button BTN;
    public float btnDelay = .5f;
    
    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    
    void Update()
    {
        healthText.text = playerHp.ToString();
        if (Input.GetMouseButtonDown(0))
        {
            Jump();
        }
    
        if (playerHp < 0)
        {
            Destroy(this.gameObject);
            SceneManager.LoadScene("GameOver");
        }
    }
    
    public void Jump()
    {
        coroutine = ButtonDelayed(btnDelay);
        StartCoroutine(coroutine);
        rb.AddForce(Vector2.up * downForce + Vector2.right * speed, 
        ForceMode2D.Impulse);
        rb.isKinematic = false;
    }
    
    IEnumerator ButtonDelayed(float delay)
    {
        BTN.interactable = false;
        yield return new WaitForSeconds(delay);
        BTN.interactable = !BTN.interactable;
    }
    

    【讨论】:

    • 我还是个新人,所以我该如何准确地放置协程?我也是第一次使用 IEnumerator
    • 编辑了帖子并更改了您的脚本。
    【解决方案2】:

    我还是无法回复 cmets,所以我会在这里发帖

    使用 IEnumerator 就像使用其他函数一样

    你把它放在你的代码中,然后调用它 不同的是当你调用它时你添加了

    StartCoroutine(MethodName()) ;

    它将运行代码的第一部分 - 然后等待您指定的时间量,然后它将运行代码的第二部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多