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 天前
C语言学习笔记 - 20.C编程预备计算机专业知识 - 变量为什么必须的初始化【重点】
c语言·笔记·学习
kobesdu1 天前
【ROS2实战笔记-12】rosshow:终端里的盲文可视化与无头机器人的现场调试
笔记·机器人·ros·移动机器人
sakiko_1 天前
UIKit学习笔记1-创建项目(使用UIKit)、使用组件
笔记·学习
智者知已应修善业1 天前
【51单片机中的打飞机设计】2023-8-25
c++·经验分享·笔记·算法·51单片机
czhc11400756631 天前
C# 428 线程、异步
开发语言·c#
董董女友1 天前
unity mcp 配置指南
unity·游戏引擎
唐青枫1 天前
C#.NET ThreadLocal 深入解析:线程独享数据、性能收益与实战边界
c#·.net
智者知已应修善业1 天前
【51单片机按键调节占空比3位数码管显示】2023-8-24
c++·经验分享·笔记·算法·51单片机
JasmineX-11 天前
数据结构(笔记)——双向链表
c语言·数据结构·笔记·链表
程序猿乐锅1 天前
【Tilas|第三篇】多表SQL语句
数据库·经验分享·笔记·学习·mysql