我写了这个剧本,出于某种原因,我离开地面后最多可以跳两次。这真的很奇怪,因为正如你所看到的,maxJumps被设置为1。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float horizontal;
private float speed = 8f;
private float jumpingPower = 16f;
private bool isFacingRight = true;
private bool isGrounded = false;
public float maxJumps = 1;
private float currentJumps;
public float coyoteTimerMax = .03f;
private float coyoteTimer;
private float jumpBuffer;
public float maxJumpBuffer = .04f;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump"))
{
jumpBuffer = maxJumpBuffer;
}
if (isGrounded)
{
currentJumps = 0;
coyoteTimer = coyoteTimerMax;
}
else
{
coyoteTimer -= Time.deltaTime;
}
jumpBuffer -= Time.deltaTime;
if (jumpBuffer > 0 && coyoteTimer > 0 && currentJumps < maxJumps)
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
currentJumps++;
jumpBuffer = 0; // Reset the jump buffer after successfully jumping
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}