[英]Unity2D how to limit player jump
所以我正在制作一個點擊游戲,這是我的代碼。 我想問的是如何限制按鈕點擊,所以它不能被多次點擊,因為如果我多次點擊它,速度就會變得太快
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;
}
public Button BTN;
public float btnDelay = .5f;
獲取 Button 引用並指定持續時間
coroutine = ButtonDelayed(btnDelay);
StartCoroutine(coroutine);
這在你調用Jump();
之后在您的更新或Jump()
中
IEnumerator ButtonDelayed(float delay)
{
BTN.interactable = false;
yield return new WaitForSeconds(delay);
BTN.interactable = !BTN.interactable;
}
這個地方。 只是一個快速的模型。 不知道你是否會得到一個例外。 如果你有問題就打我。
編輯:我忘了告訴你將檢查器中禁用的 state 的顏色更改為按鈕可交互時的顏色。 否則,您將看到 Button 更改 colors。
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 就像任何其他 function
你把它放在你的代碼中的某個地方然后調用它不同的是當你調用它時你添加
啟動協程(方法名());
它將運行代碼的第一部分 - 然后等待您指定的時間量,然后它將運行代碼的第二部分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.