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);
    }
}
相关推荐
不太可爱的叶某人1 小时前
【学习笔记】Java并发编程的艺术——第6章 Java并发容器和框架
java·笔记·学习
做一位快乐的码农2 小时前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
SmalBox2 小时前
【渲染流水线】[几何阶段]-[归一化NDC]以UnityURP为例
unity·渲染
DavieLau2 小时前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
超勇的阿杰2 小时前
gulimall项目笔记:P54三级分类拖拽功能实现
android·笔记
张人玉2 小时前
C#Encoding
开发语言·c#
饕餮争锋3 小时前
设计模式笔记_行为型_策略模式
笔记·设计模式·策略模式
₯㎕星空&繁华4 小时前
Linux-地址空间
linux·运维·服务器·经验分享·笔记
hqwest4 小时前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
诗书画唱4 小时前
学习笔记与效率提升指南:编程、记忆与面试备考
笔记·学习·面试