[英]I'm try to make game using unity and my Jump functionality not working
我正在嘗試按照教程制作簡單的 2D 游戲,當我做與教程相同的事情時,我的跳躍功能不起作用,左右移動功能起作用,請在下面幫助我,我附上了我的源代碼和相關屏幕截圖
我的播放器類
public class Player : MonoBehaviour
{
private Rigidbody2D _rigid;
//variable for jump
[SerializeField]
private float _jumpForce = 5.0f;
[SerializeField]
private LayerMask _grondLayer;
private bool _resetJump = false;
// Start is called before the first frame update
void Start()
{
_rigid = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
float move = Input.GetAxisRaw("Horizontal");
_rigid.velocity = new Vector2(move,_rigid.velocity.y);
if(Input.GetKeyDown(KeyCode.Space) && IsGrounded()==true)
{
Debug.Log("jump");
_rigid.velocity = new Vector2(_rigid.velocity.x,_jumpForce);
StartCoroutine(ResetJumpNeededRoutine());
}
}
bool IsGrounded()
{
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, _grondLayer);
if(hitInfo.collider != null)
{
if(_resetJump==false){return true;}
}
return false;
}
IEnumerator ResetJumpNeededRoutine()
{
_resetJump = true;
yield return new WaitForSeconds(0.1f);
_resetJump = false;
}
}
在二維字符上實現跳轉機制的正確方法。
_rigid.AddForce(new Vector2(0, _jumpForce), ForceMode2D.Impulse);
問題可能是您選擇的Ground
層的 LayerMask 被忽略,因此IsGrounded
函數將返回 false。
您想要做的是在統一編輯器中選擇您希望 Raycast 忽略的圖層(我假設除Ground
之外的所有圖層),然后再試一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.