Unity中wheelcollider组件的基本使用方法总结

    xiaoxiao2022-07-07  211

    ----前言----unity中的wheelcollider确实是一个比较麻烦的组件,对于初学者来说,可能需要不断去进行实践练习,慢慢地去理解掌握它,一味强吃是不行的。 进入正题 -----一、对赛车的设置 ---------***首先,为了方便管理,把控制的赛车中的四个车轮放在一个whell空物体中(该空物体是car的子物体)然后在car中新建一个名为wheelCollider的空子物体,在wheelCollider中再新建四个空物体,分别命名为LB(左后轮)、RB(右后轮)、LF(左前轮)、RF(右前轮),然后给四个物体加上wheelCollider组件通过移动空物体使wheelcollider能够处于对应车轮的位置,通过调整wheelcollider组件中的Radius参数来使wheel collider能与车轮重合(尽量重合)。需要注意的一点是,尽量要保证每个轮的wheelcollider中的坐标参数相同,尽量保证这四个空物体的y坐标相同。(否则很容易出现运行游戏时车辆不平稳的情况). 最后给车整体对象car加上Rigidbody组件,并将质量Mass设置为较大的值以提高模拟的真实性(建议设为2000左右)。 如图Car为父物体。加了Rigidbody。 —二、对相机的控制(跟随赛车) 新建一个c#脚本,命名为Follow.cs。 如下: using System.Collections; using System.Collections.Generic; using UnityEngine;

    public class Follow : MonoBehaviour {

    private Transform target; private Vector3 fixedDistance; private Vector3 tempPos; void Start() { target = GameObject.FindGameObjectWithTag("Player").transform;//找到标签为Player的目标物体 fixedDistance = new Vector3(0, 3.35f, -7.33f);//相机处于赛车背后的初始位置,需要进行测试 } void FixedUpdate() { //transformDirection(new Vector3)可以将Vector3的坐标转换为世界坐标; tempPos = target.TransformDirection(fixedDistance) + target.position; transform.position = Vector3.Lerp(transform.position, tempPos, Time.fixedDeltaTime * 3); transform.LookAt(target);//使相机自身z坐标对齐物体的自身z坐标(注意不是世界坐标) }

    } *-----将该脚本挂在摄像机物体上,并将Car物体的Tag设置为Player; *------三,控制赛车 新建脚本名为 PlayerController using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController: MonoBehaviour {

    private float horizontal; private float vertical; private MeshRenderer[] wheelMesh; private WheelCollider[] wheelCollider; private float maxDigree ; private float maxMotor; private void Start() { maxDigree = 30; maxMotor = 300; //rg =GetComponent<Rigidbody>(); wheelMesh = transform.GetChild(1).GetComponentsInChildren<MeshRenderer>(); wheelCollider = transform.GetChild(4).GetComponentsInChildren<WheelCollider>(); } private void FixedUpdate() { horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); Move(); } void Move() { for (int i = 0; i < 4; i++)//汽车动力 { if (i < 2) { wheelCollider[i].steerAngle = -horizontal * maxDigree; } wheelCollider[i].motorTorque = maxMotor * vertical; } for (int j = 0; j < 4; j++)//轮胎旋转 { wheelMesh[j].transform.localRotation = Quaternion.Euler(wheelCollider[j].rpm / 60 * 360, -wheelCollider[j].steerAngle, wheelMesh[j].transform.localRotation.z); } }

    } 注意:wheelMesh和wheelcollider在获取Car的子对象时要注意i的取值。 **--------//transform.GetChild(i)方法可以获取该脚本所挂物体的第i+1个子物体对象。 **--------//例如transform.GetChild(0)获取该物体的第一个子物体。 上述PlayerController脚本对应的父物体和子物体的设置如下图: Wheels是第i=1个子物体,wheeCollider是第i=4个子物体。

    OK,现在保存所有工作,点击运行,赛车就可以跑起来了0.0。 (第一次这么用心去写一篇博客真的好累,但是又复习了一遍知识还是很开心的=.=)

    最新回复(0)