2D游戏跳跃下落速度问题
有些2D游戏会感觉到向上跳跃和下落速度不一致,感觉下落时更干脆一些,比如马里奥,不过也跟具体的项目需求手感有关系。 直接上代码。下面是优化下落速度手感的代码。
using UnityEngine;
public class BetterJump : MonoBehaviour
{
public float fallMultiplier = 2.5f; //下落速度倍数
public float lowJumpMultiplier = 2f; //长按跳跃
bool isPressJump;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent();
}
public void Update()
{
if(Input.GetButton("Jump"))
{
isPressJump = true;
}
else
{
isPressJump = false;
}
}
public void FixedUpdate()
{
if(rb.velocity.y 0 && !isPressJump) //不按跳跃时减缓跳跃(如马里奥)
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
}
跳跃手感优化
如果操作都放在Update中有时会出现跳跃手感不一致的情况。 优化跳跃手感的核心思路就是按键检测放在Update中,物理相关的放到FixedUpdate中。 代码示例
public Transform groundCheck; //玩家脚底
public LayerMask ground; //地面layer
public float jumpForce;
public bool isGround, isJump, isJumpPressed;
private void Update()
{
if(Input.GetButtonDown("Jump"))
{
isJumpPressed = true;
}
}
private void FixedUpdate()
{
isGround = Physics2D.OverlapCircle(groundCheck.position, 0.1f, ground);
if (isJumpPressed && isGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isJumpPressed = false;
}
}