Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to clamp rotation of wheels along longitudinal axis ?

Discussion in 'Scripting' started by u_rs, May 27, 2017.

  1. u_rs

    u_rs

    Joined:
    Jan 5, 2016
    Posts:
    147
    My wheels are wobbling, but I thought may be clamping rotation along longitudinal (Z) axis would help.


    I used this code taken from WheelColliderTutorial:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. [System.Serializable]
    6. public class AxleInfo {
    7.     public WheelCollider leftWheel;
    8.     public WheelCollider rightWheel;
    9.     public bool motor;
    10.     public bool steering;
    11. }
    12.  
    13. public class CarController : MonoBehaviour {
    14.     public List<AxleInfo> axleInfos;
    15.     public float maxMotorTorque;
    16.     public float maxSteeringAngle;
    17.  
    18.     // finds the corresponding visual wheel
    19.     // correctly applies the transform
    20.     public void ApplyLocalPositionToVisuals(WheelCollider collider)
    21.     {
    22.         if (collider.transform.childCount == 0) {
    23.         return;
    24.         }
    25.  
    26.         Transform visualWheel = collider.transform.GetChild(0);
    27.  
    28.         Vector3 position;
    29.         Quaternion rotation;
    30.         collider.GetWorldPose(out position, out rotation);
    31.  
    32.         visualWheel.transform.position = position;
    33.         visualWheel.transform.rotation = rotation;
    34.     }
    35.  
    36.     public void FixedUpdate()
    37.     {
    38.         float motor = maxMotorTorque * Input.GetAxis("Vertical");
    39.         float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
    40.  
    41.         foreach (AxleInfo axleInfo in axleInfos) {
    42.         if (axleInfo.steering) {
    43.             axleInfo.leftWheel.steerAngle = steering;
    44.             axleInfo.rightWheel.steerAngle = steering;
    45.         }
    46.         if (axleInfo.motor) {
    47.             axleInfo.leftWheel.motorTorque = motor;
    48.             axleInfo.rightWheel.motorTorque = motor;
    49.         }
    50.         ApplyLocalPositionToVisuals(axleInfo.leftWheel);
    51.         ApplyLocalPositionToVisuals(axleInfo.rightWheel);
    52.         }
    53.     }
    54. }

    (
    I have empty object with WheelCollider, it has child - visualWheel with mesh.
    I think visualWheel should be clamped, because it seems only mesh is wobbling but not parent object with WheelCollider.

    More details about this problem: https://forum.unity3d.com/threads/wobbling-wheels.472638/)
     

    Attached Files:

    Last edited: May 27, 2017