您当前的位置: 首页 >  游戏
  • 8浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 2D游戏跳跃优化

我寄人间雪满头丶 发布时间:2022-05-04 02:52:15 ,浏览量:8

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;
        }
    }
关注
打赏
1648518768
查看更多评论
立即登录/注册

微信扫码登录

0.0707s