WheelCollider

作者:追风剑情 发布于:2019-10-19 12:10 分类:Unity3d

参考:https://www.taikr.com/article/536

车轮碰撞器

一、工程截图

1111.png

3333.png

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 参考 https://www.taikr.com/article/536
/// WheelCollider
/// 官方文档 https://docs.unity3d.com/Manual/class-WheelCollider.html
/// 汽车控制器
/// </summary>
public class CarController : MonoBehaviour
{
    //车轮碰撞器
    public WheelCollider FrontLeftWheel;
    public WheelCollider FrontRightWheel;
    public WheelCollider BackLeftWheel;
    public WheelCollider BackRightWheel;

    //车轮模型Transform
    public Transform FrontLeftTransform;
    public Transform FrontRightTransform;
    public Transform BackLeftTransform;
    public Transform BackRightTransform;

    //引擎力矩(控制汽车前进动力大小, 正值前进,负值后退)
    public float motorTorque = 0;
    //控制车轮转角(正值向右转,负值向左转)
    public float steerAngle = 0;
    //变速箱齿轮系数,可以通过这个系数模拟档位
    public float gearRatio = 1;
    //引擎转速
    private float m_EngineRPM = 0;

    private Vector3 rotate = Vector3.zero;

    void Update()
    {
        //模拟前驱
        FrontLeftWheel.motorTorque = motorTorque;
        FrontRightWheel.motorTorque = motorTorque;

        //转向
        FrontLeftWheel.steerAngle = steerAngle;
        FrontRightWheel.steerAngle = steerAngle;

        //rpm: 每分钟多少转
        //通过两个前轮平均转速计算引擎转速
        float average = (FrontLeftWheel.rpm + FrontRightWheel.rpm) / 2;
        m_EngineRPM = average * gearRatio;

        //根据车轮转速旋转车轮模型
        if (average > 1)
        {
            float rps = average / 60;//每秒多少转
            float angle = rps * 360; //每秒旋转多少度(欧拉角)
            rotate.x = angle * Time.deltaTime;//每帧旋转多少度(欧拉角)
            FrontLeftTransform.Rotate(rotate);
            FrontRightTransform.Rotate(rotate);
            BackLeftTransform.Rotate(rotate);
            BackRightTransform.Rotate(rotate);
        }
    }
}

运行测试

22225.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号