我创建了一个小型的侧面滚动运动。
private Rigidbody2D rigid;
private BoxCollider2D playerCollider;
private bool isMovingRight = false;
private Vector2 movement;
private bool jumpPressed;
private const int MOVEMENT_SPEED = 5;
private const int JUMP_POWER = 5;
private const float GROUNDCHECK_TOLERANCE_SIDE = 0.05f;
private const float GROUNDCHECK_TOLERANCE_BOTTOM = 0.05f;
private void Start()
{
rigid = GetComponent<Rigidbody2D>();
playerCollider = GetComponent<BoxCollider2D>();
}
private void Update()
{
SetMovement();
}
private void FixedUpdate()
{
Move();
}
private void SetMovement()
{
float horizontalMovement = Input.GetAxis("horizontal") * MOVEMENT_SPEED;
if (Input.GetButtonDown("Jump"))
{
jumpPressed = true;
}
movement = new Vector2(horizontalMovement, rigid.velocity.y);
}
private void Move()
{
if (GroundCheck(true) || GroundCheck(false))
{
if (jumpPressed)
{
movement.y = JUMP_POWER;
jumpPressed = false;
}
}
rigid.velocity = movement;
}
private bool GroundCheck(bool checkLeftSide)
{
Bounds colliderBounds = playerCollider.bounds;
Vector2 rayPosition = colliderBounds.center;
float horizontalRayPosition = colliderBounds.extents.x + GROUNDCHECK_TOLERANCE_SIDE;
if (checkLeftSide)
{
rayPosition.x -= horizontalRayPosition;
}
else
{
rayPosition.x += horizontalRayPosition;
}
return Physics2D.Raycast(rayPosition, Vector2.down, (playerCollider.size.y / 2) + GROUNDCHECK_TOLERANCE_BOTTOM);
}
我在Update中注册输入并在FixedUpdate中处理Physics。当按下跳跃按钮时,玩家跳跃工作正常。
但是当多次按下跳跃时,玩家会在空中跳起来,然后再跳下来跳一次。
因此,如果按下按钮超过1次,玩家将在完成第一次跳跃后再次跳跃。
我该如何避免这种行为?
答案 0 :(得分:2)
使用您的代码,我添加了2条评论和其他声明,以澄清我在评论中的含义。这应该可以解决您的问题。
private void SetMovement()
{
float horizontalMovement = Input.GetAxis("horizontal") * MOVEMENT_SPEED;
if (Input.GetButtonDown("Jump"))
{
// Only ever gets set to false if you are grounded and it makes you jump.
// Should only be set to true if you can jump. So you could add your groundChecks here...
// or use the method I am showing
jumpPressed = true;
}
movement = new Vector2(horizontalMovement, rigid.velocity.y);
}
private void Move()
{
if (GroundCheck(true) || GroundCheck(false))
{
if (jumpPressed)
{
movement.y = JUMP_POWER;
// This was the only place this every was set to false, and
// specific conditions were required to make this happen.
jumpPressed = false;
}
}
// fastest way to test
else
{
// yes they pressed jump but they can't jump so reset it, now
// they wont jump as soon as they land. just because they got
// trigger happy.
jumpPressed = false;
}
rigid.velocity = movement;
}