[英]How do I use Input.GetButton() without getting several jumps at once? Unity 2D Character Controller C#
我已經制作了很多 2D 游戲,你是屏幕上的一個東西,然后你跳來跳去等等,但是在我最新的項目中,三角形運行(幾何沖刺,但更糟),我希望能夠按住鼠標和角色你知道,以均勻的速度跳躍,就像在幾何沖刺中一樣,所以我沒有使用Input.GetButtonDown
,而是將其替換為Input.GetButton
,然后我放了一個return;
在if
語句之后,因此每個Update()
只能運行一個if
(即它所在的 function),但這使得除了最快的點擊之外,任何東西都可以將播放器啟動到正常跳躍高度的 10-20 倍。 我嘗試了很多不同的方法來確保if
語句在每個Update()
中只運行一次,這讓角色控制器有足夠的時間來檢查玩家是否接地以允許或阻止跳躍,所以我不知道為什么它讓我興奮起來。 編輯:使用Input.GetButtonDown
一切正常。
到目前為止,這是玩家運動的全部代碼,我剛剛開始游戲,所以還沒有太多代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
bool jump = false;
public Rigidbody2D rb;
public float moveSpeed = 10f;
public Transform transform;
private float moveY = 0f;
private int jumpCounter = 0;
private bool jumpIf = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Jump") && jumpIf) // if we press the jump button
{
jump = true; // set jump bool to true (see void fixedupdate for more)
jumpIf = false;
}
else
{
jump = false;
}
jumpIf = true;
return;
}
void FixedUpdate() // called a set amount of times per second, used with physics movement etc lol
{
controller.Move(0f, false, jump); // move in which direction, are we crouching, are we jumping
jump = false;
moveY = rb.velocity.y;
rb.velocity = new Vector2(moveSpeed, moveY);
}
}
如您所見,在if
中,它非常混亂,因為我最終嘗試了各種事情。
非常感謝!
您是否嘗試在帶有 if 語句的FixedUpdate
中使用GetButtonUp
? 我在Update
中的交互有類似的問題。 在Update
上使用GetButton
將使游戲在您開始按下跳轉鍵后每幀都執行跳轉,而使用GetButtonUp
則只有在松開跳轉鍵時才會執行操作。 像這樣的東西可能會起作用:
void FixedUpdate()
{
if (Input.GetButtonUp("Jump")) // if we press the jump button
{
jump = true; // set jump bool to true, in case you want to use it for an animation,etc.
//Jump code here.
controller.Move(0f, false, jump);
moveY = rb.velocity.y;
rb.velocity = new Vector2(moveSpeed, moveY);
}
}
或者在Update
中使用CoRoutine並yield return new WaitForSeconds()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.