栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity 2D游戏跳跃优化

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity 2D游戏跳跃优化

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) //下落速度
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        else 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;
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898200.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号