Search Unity

Simple Car (HingeJoint / JointMotor / Code Problem)

Discussion in 'Getting Started' started by Napivo, Feb 12, 2015.

  1. Napivo

    Napivo

    Joined:
    Feb 9, 2015
    Posts:
    39
    I read somewhere it is quite easy to build a simple car.

    - take a Cube for the body
    Make it a Rigid Body


    - Take a cylinder for the wheel
    Make It a Rigid Body
    Attach a hinge from the wheel to the body
    Make Mesh collider and cylinder

    Copy 4 times and we have a car :)

    This works great. when I give the motor of one of the joints Target Velocity and Force in the UI it even drives!!!

    Then I tried it from script but it doesn't work at all.

    Does anyone know why?

    Below is the code I use. It accepts no input and both Start and FixedUpdate get called. DriveWheels are also set. I checked.

    Many thanks for your time.



    Code (CSharp):
    1. public class PlayerControll : MonoBehaviour {
    2.  
    3.     public Rigidbody DriveWheelLeft;
    4.     public Rigidbody DriveWheelRight;
    5.  
    6.     private HingeJoint HingeJointLeft;
    7.     private HingeJoint HingeJointlRight;
    8.  
    9.     private JointMotor JointMotorLeft;
    10.     private JointMotor JointMotorRight;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         HingeJointLeft = DriveWheelLeft.hingeJoint;
    15.         HingeJointlRight = DriveWheelRight.hingeJoint;
    16.  
    17.         JointMotorLeft = HingeJointLeft.motor;
    18.         JointMotorRight = HingeJointlRight.motor;
    19.     }
    20.    
    21.     // Update is called once per frame
    22.     void FixedUpdate ()
    23.     {
    24.         HingeJointLeft.useMotor = true;
    25.         HingeJointlRight.useMotor = true;
    26.  
    27.         JointMotorLeft.freeSpin = false;
    28.         JointMotorRight.freeSpin = false;
    29.  
    30.         JointMotorLeft.force = 100;
    31.         JointMotorLeft.targetVelocity = 100;
    32.  
    33.         JointMotorRight.force = 100;
    34.         JointMotorRight.targetVelocity = 100;
    35.     }
    36. }
     
  2. ADoby

    ADoby

    Joined:
    Dec 10, 2012
    Posts:
    21
    For some reason JointMotor or HingeJoint.motor does not equal referenz to that specific motor.
    You have to do this every FixedUpdate

    Code (CSharp):
    1. JointMotorLeft = HingeJointLeft.motor;
    2. JointMotorLeft.force = 100;
    3. JointMotorLeft.targetVelocity= 100;
    4. HingeJointLeft.motor = JointMotorLeft;
    I don't know why it has to be like that. It seems like the physics in Unity need some work.