作者:sfktrd | 来源:互联网 | 2023-09-12 15:23
当我做与教程相同的事情时,我试图按照教程制作简单的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();
}
// 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;
}
}
在2D角色上实现跳转机制的正确方法。
_rigid.AddForce(new Vector2(0,_jumpForce),ForceMode2D.Impulse);
,
问题可能是您选择的Ground
图层被忽略,因此IsGrounded
函数将返回false。
您想要做的是在统一编辑器中选择要忽略的Raycast图层(我假设除Ground
以外的所有图层),然后再进行选择。