How to Make The Wheel Mesh Renderer At the Wheelcollider Position Unity

Viewed 2863

I am having a little trouble figuring out how to make the wheels mesh render er object match up with the Wheelcollider object. I have searched the internet and found a few brief answers for a different version of unity.

Here is my current code:

using UnityEngine; using System.Collections;

public class Position : MonoBehaviour {

    public WheelCollider wc;
    public Transform tf;

    // Use this for initialization
    void Start () {

        wc = GetComponent<WheelCollider> ();
        tf = GetComponent<Transform> ();

    }

    // Update is called once per frame
    void Update () {

        transform.position = new Vector3 (tf.transform.position.x + (wc.suspensionDistance * 100), tf.transform.position.y);

I have know idea how to make this work please help!

2 Answers

Neither the OP's code, nor the accepted answer are correct.

The OP's code is bad because it puts the wheel at the wrong position (it's right sometimes, but usually wrong); and the accepted answer is wrong because it says you don't need code to achieve this.

Per the Official Unity Tutorial for Wheel Colliders you need to call GetWorldPose to acquire the pose of the wheel, and then you need to transfer that pose to the object which renders the wheel each frame. (That means that the MeshRenderer and the Collider do need to be on different objects.) -- Hierarchy alone won't work, since the transform of the parent is not modified by the wheel collider (i.e. it will just stay at 0,0,0 forever even if the wheel is bouncing around and spinning, etc.)

Though, I do recommend the same hierarchy as proposed in the accepted answer, as it makes things easier to manage:

  • Vehicle
    • WheelCollider1
      • WheelMeshRenderer1
    • WheelCollider2
      • WheelMeshRenderer2
    • etc...

Here's an example MonoBehavior script that will work if you attach it to each of the WheelMeshRenderer# objects (per the hierarchy above):

private WheelCollider wheelCollider;
private void Start()
{
    // Once, at startup, search up the tree for the nearest wheel collider,
    // and grab a reference to it.
    wheelCollider = GetComponentInParent<WheelCollider>();
}

private void FixedUpdate()
{
    // Each physics update, get the pose of the wheel in World space coordinates.
    wheelCollider.GetWorldPose(out var pos, out var rot);

    // Apply that pose to this object's transform.
    transform.position = pos;
    transform.rotation = rot;
}
Related