Unity实现不倒翁

Unity实现不倒翁

Unity 实现不倒翁

不倒翁插件下载地址
这是一个下载地址

https://www.aigei.com/item/zekpackage_unit.html

请使用URP渲染管线创建工程,导入此插件,有问题评论区告诉我。
备用下载地址:B站

csharp 复制代码
using UnityEngine;


[RequireComponent(typeof(Rigidbody))]
public class RolyPoly : MonoBehaviour
{

    [Header("重心设置")]
    [Tooltip("重心高度偏移(负值降低重心)")]
    public float centerOfMassOffset = -0.25f;

    [Header("物理参数")]
    [Range(0.1f, 10f)] public float angularDrag = 2f;
    [Range(0.1f, 10f)] public float maxAngularVelocity = 8f;

    private Rigidbody rb;
    private Vector3 originalCenterOfMass;
    
    [Header("摇摆优化")]
    public float stabilizationForce = 5f;

  /*  参数、作用、推荐值
centerOfMassOffset  重心越低越稳定	(-0.5,  -1.5)
angularDrag 旋转阻力,值越大停止越快	(1.0, 3.0)
maxAngularVelocity 最大旋转速度	(5, 10)
stabilizationForce 主动稳定力度	(2, 5)
*/

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.maxAngularVelocity = maxAngularVelocity;
        rb.angularDrag = angularDrag;

        // 设置重心
        originalCenterOfMass = rb.centerOfMass;
        AdjustCenterOfMass();
    }

    void AdjustCenterOfMass()
    {
        // 降低重心(Y轴负方向)
        Vector3 newCenter = originalCenterOfMass;
        newCenter.y += centerOfMassOffset;
        rb.centerOfMass = newCenter;
    }
    void FixedUpdate()
    {
        // 增加稳定性
        if (rb.velocity.magnitude < 0.1f)
        {
            Vector3 uprightDirection = Vector3.up;
            Vector3 currentUp = transform.up;

            // 计算恢复力矩
            Vector3 torque = Vector3.Cross(currentUp, uprightDirection);
            rb.AddTorque(torque * stabilizationForce, ForceMode.Acceleration);
        }
    }
    // 可选:在编辑器中可视化重心
    void OnDrawGizmosSelected()
    {
        if (!Application.isPlaying) return;

        Gizmos.color = Color.red;
        Gizmos.DrawSphere(transform.TransformPoint(rb.centerOfMass), 0.1f);
    }
}
相关推荐
Ccjf酷儿6 分钟前
操作系统 李治军 4 设备驱动与文件系统
笔记
Monkey_Xuan15 分钟前
C#中的引用传递和值传递
unity·c#
CreasyChan38 分钟前
C# LINQ 深度解析:优缺点与性能陷阱
unity·c#·游戏开发
大白的编程日记.1 小时前
【计算网络学习笔记】Socket编程UDP实现简单聊天室
网络·笔记·学习
精神小伙就是猛1 小时前
C# sealed密封 追本溯源
开发语言·c#
中屹指纹浏览器2 小时前
2025技术综述:指纹浏览器与国内IP适配的核心技术优化与实践
经验分享·笔记
im_AMBER2 小时前
weather-app开发手记 02 JSON基础 | API 调用 400 错误修复 | JWT 认证问题
笔记·学习·json·axios·jwt
阿蒙Amon2 小时前
JavaScript学习笔记:1.JavaScript简介
javascript·笔记·学习
雨季6663 小时前
C 语言学习指南:从入门到实战的系统路径
c#
Vincent_Zhang2333 小时前
专题:通过时间轴解释区分各种时态
笔记