返回首页DA系统C#IDE文件同步服务屏保 今天是: 2026-05-05    "立夏"  夏季的第一个节气,表示盛夏时节的正式开始

搜索
热搜: linux 技术
Hi~登录注册
查看: 1566|回复: 0

[原创] 【原创】Unity给角色添加Rigidbody2D的物理推力时,避免角色倾斜

[复制链接]
发表于 2024-6-5 09:07:26 | 显示全部楼层 |阅读模式

少侠不来段修仙之旅吗~

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
Unity给角色添加Rigidbody2D的物理推力时,避免角色倾斜



实际上这个问题问的就是如何避免角色旋转角度过大,那解决问题的答案就出来了,可以在update生命周期使用代码限制角色x,y轴的旋转角度2D角色限制z轴),案例如下(Rigidbody2D案例):

    private float PlayerJumpTime=0;

    private float PlayerMoveSpeed = 300;

    private void Start()
    {
        PlayerRigidbody = PlayerGameObj.GetComponent<Rigidbody2D>();
    }


    private void Update()
    {
        //固定角色平衡
        PlayerTF.rotation = new Quaternion(PlayerTF.rotation.x, PlayerTF.rotation.y, 0, 0);

        //模块开启停止移动
        if (GameManager_Script.TimeSetPanelISOpen==false)
        {
            //移动角色
            //模拟一个向Vector3各种方向的的力,力度为300的运动
            if (Input.GetKey(KeyCode.D))
            {
                PlayerRigidbody.AddForce(Vector3.right * PlayerMoveSpeed);
                //print("向右走");
            }

            if (Input.GetKey(KeyCode.A))
            {
                PlayerRigidbody.AddForce(Vector3.left * PlayerMoveSpeed);
                //print("向左走");
            }

            if (Input.GetKey(KeyCode.Space))
            {
                //控制跳跃的时间,不然会跳跃出边界
                if (PlayerJumpTime < 0.3f)
                {
                    PlayerJumpTime = PlayerJumpTime + Time.deltaTime;
                    print(PlayerJumpTime);

                    PlayerRigidbody.AddForce(Vector3.up * PlayerMoveSpeed);
                    //print("跳");
                }
                else
                {
                    PlayerRigidbody.AddForce(Vector3.down * PlayerMoveSpeed);
                }

            }
            else
            {
                PlayerJumpTime = 0;

                PlayerRigidbody.AddForce(Vector3.down * PlayerMoveSpeed);
            }
        }

    }

游客
回复
*滑块验证:

DA论坛飞机票来了~
快速回复 返回顶部 返回列表