unity 车轮碰撞器 (一)

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

//教程网址 https://docs.unity3d.com/Manual/WheelColliderTutorial.html
[System.Serializable]
public class SimpleCarController : MonoBehaviour
{
    public List<AxleInfo> axleInfos; // the information about each individual axle
    public float maxMotorTorque; // maximum torque the motor can apply to wheel 车轮上的最大动力
    public float maxSteeringAngle; // maximum steer angle the wheel can have  最大转角

    public void FixedUpdate()
    {
        float motor = maxMotorTorque * Input.GetAxis("Vertical");
        float steering = maxSteeringAngle * Input.GetAxis("Horizontal");

        foreach (AxleInfo axleInfo in axleInfos)
        {
            if (axleInfo.steering)
            {
                axleInfo.leftWheel.steerAngle = steering;
                axleInfo.rightWheel.steerAngle = steering;
            }
            if (axleInfo.motor)
            {
                axleInfo.leftWheel.motorTorque = motor;
                axleInfo.rightWheel.motorTorque = motor;
            }
            ApplyLocalPositionToVisuals(axleInfo.leftWheel);
            ApplyLocalPositionToVisuals(axleInfo.rightWheel);
        }

    }
    // finds the corresponding visual wheel
    // correctly applies the transform
    public void ApplyLocalPositionToVisuals(WheelCollider collider)
    {
        if (collider.transform.childCount == 0)
        {
            return;
        }

        Transform visualWheel = collider.transform.GetChild(0);

        Vector3 position;
        Quaternion rotation;
        collider.GetWorldPose(out position, out rotation);

        visualWheel.transform.position = position;
        //visualWheel.transform.rotation = rotation;
    }
}
//侧轮轱辘
[System.Serializable]
public class AxleInfo
{
    public WheelCollider leftWheel;//左轮
    public WheelCollider rightWheel;//右轮
    public bool motor; // is this wheel attached to motor? 是否提供动能
    public bool steering; // does this wheel apply steer angle?  是否能转向
}


创建车子,模型和车轮碰撞器分开,方便操作

在Car上挂载脚本,配置如下:

运行,俺wasd即可移动转弯,在地面上放些障碍物,还可实现颠簸效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值