我正在尝试让我的 2D 统一角色跳跃



正如我所说,我试图让我的角色在 Unity 中跳跃,但当我点击空格时没有任何反应,Unity 也没有抛出任何错误。

public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
[SerializeField]
public float jumpSpeed;
private Animator myAnimator;
[SerializeField]
private float movementSpeed;
private bool facingLeft;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
private bool isGrounded;
private bool jump;
[SerializeField]
private float jumpForce;
// Start is called before the first frame update
void Start()
{
facingLeft = true;
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
isGrounded = IsGrounded();
HandleMovement(horizontal);
flip(horizontal);
}
private void HandleMovement(float horizontal)
{
myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
if (isGrounded && jump)
{
isGrounded = false;
myRigidbody. AddForce(new Vector2(0, jumpForce));
}
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
}
private void flip(float horizontal)
{
if (horizontal < 0 && !facingLeft || horizontal > 0 && facingLeft)
{
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded()
{
if (myRigidbody.velocity.y <= 0)
{
foreach (Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
return true;
}
}
}
}
return false;
}
}

我一直在遵循本教程,他的跳跃,但我的不是。我认为这可能与我设置基础点的方式有关,但我不确定这是代码中的错误还是在 Unity 中。

您不会在任何地方调用 HandleInput。

添加到固定更新

void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
isGrounded = IsGrounded();
HandleMovement(horizontal);
flip(horizontal);
HandleInput(); // add this so you are sampling input
}

最新更新