Search Unity

Rolling Wheel as a character : dealing with rotations

Discussion in 'Scripting' started by VincentAbert, May 5, 2020.

  1. VincentAbert

    VincentAbert

    Joined:
    May 2, 2020
    Posts:
    123
    Hey everyone !
    I'm very new to unity and programming, and I'm trying to create a controller for a wheel character (you litterally play a loose wheel rolling), for which I want to use rigidbody. Since the wheel is constantly rotating, I used another object (that copies the wheel's position) that controls its y rotation (turning left/right) and where "forward" is (since its z axis is constantly turning). It works pretty well, except from the fact that the wheel stops rotating on the X axis when it reaches 90 or -90 rotation, I spent a lot of time trying things, but I couldn't do it on my own. Here is what I have so far (in case this is isn't clear, the RotationTarget is an empty that copies the Character's position, and whose Yrotation is instructed by the keyboard) :

    Code (CSharp):
    1.  public class CharacterMovement : MonoBehaviour
    2.      {
    3.    
    4.      
    5.          private Rigidbody rb;
    6.    
    7.          public GameObject RotationTarget;
    8.    
    9.          private Transform TargetTransform;
    10.      
    11.    
    12.    
    13.    
    14.          void Start ()
    15.    
    16.          {
    17.              rb = GetComponent<Rigidbody>();
    18.            
    19.          }
    20.      
    21.    
    22.          void Update()
    23.          {
    24.      
    25.            
    26.              float vertical = Input.GetAxis("Vertical");
    27.            
    28.          
    29.              // Getting the wheel to roll, works pretty well
    30.              TargetTransform = RotationTarget.GetComponent<Transform>();
    31.              rb.velocity += vertical*TargetTransform.forward * Time.deltaTime*10;
    32. // Getting the wheel to rotate on Y and Z as the Target but on X as it should as a rigidbody)
    33.              transform.rotation = Quaternion.Euler (transform.eulerAngles.x, TargetTransform.eulerAngles.y, TargetTransform.eulerAngles.z);
    34.        
    35.    
    36.    
    37.          }
    I may have gotten this completely wrong (for example I add force to the rigidbody's velocity, whereas it may have made more sense to add force to its rotation/angular velocity ? It looks good this way so I have left it as is so far), if you have a better solution I'd love to hear it

    Thanks a lot
     
  2. elliotfriesen

    elliotfriesen

    Joined:
    Mar 17, 2020
    Posts:
    71
    instead of coding the wheel to rotate you can create a animation of the wheel rotation then have the parent of that object be the movement controller