【发布时间】:2018-02-14 17:45:10
【问题描述】:
我创建了一个小的 2D 横向卷轴运动。
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 中注册 Inputs 并在 FixedUpdate 中处理 Physics。当按下跳跃按钮时,玩家可以正常跳跃。
但是当多次按下跳跃时,玩家会在空中跳起来,下来再跳一次。
因此,如果按下按钮超过 1 次,玩家将在完成第一次跳跃后进行第二次跳跃。
如何避免这种行为?
【问题讨论】:
-
这行代码
movement.y = JUMP_POWER;应该是movement.y += JUMP_POWER; -
不清楚你的目的是什么:你想在角色已经跳跃时完全禁用跳跃吗?或者在着陆前在第一个跳跃的基础上添加第二个跳跃,Metroid 风格?
-
如果你的groundcheck失败,设置
jumpPressed = false。 -
您的逻辑是“按下 Jump?好的……我在地上吗?是的,将 Jump 设置为 false。不,我不在地上?什么都不做。”你应该只有在接地的情况下才能跳跃,所以如果你的接地检查都失败了,请使用 else 将 jumpPressed 设置为 false。