Search Unity

car controler

Discussion in 'Scripting' started by joacoerazo_legacy, May 4, 2006.

  1. joacoerazo_legacy

    joacoerazo_legacy

    Joined:
    Apr 5, 2006
    Posts:
    214
    Hi,

    I made the unity scripting tutorial and I want to change one element, if the car is stoped, you are able to rotate it. I want to allow that if the car is moving only.

    Any idea on how to do it?
     
  2. hsparra

    hsparra

    Joined:
    Jul 12, 2005
    Posts:
    750
    Since you do not have a rigidbody, if you do not mind brute force you can do the following:

    1. Add a variable that is a Vector3 to hold the prior position of the car
    2. Check the distance between the current position of the car and the prior position
    3. If the distance is greater than some value, apply the turn

    Ex.
    Code (csharp):
    1.  
    2. // The Update function is called once every frame
    3.  
    4. var priorPosition : Vector3;
    5.  
    6. function Start () {
    7.     priorPosition = transform.position;
    8. }
    9.  
    10. function Update () {
    11.  
    12.     distance = Vector3.Distance(priorPosition, transform.position);
    13.     Debug.Log("v:" + distance);
    14.     priorPosition = transform.position;
    15.     // Apply motion along the z axis of the car
    16.     transform.Translate (0, 0, Input.GetAxis ("Vertical"));
    17.  
    18.     if (distance > 0.1) {
    19.         // Apply rotation around the y axis of the car
    20.        transform.Rotate (0, Input.GetAxis ("Horizontal"), 0);
    21.     }
    22. }
     
  3. joacoerazo_legacy

    joacoerazo_legacy

    Joined:
    Apr 5, 2006
    Posts:
    214
    Thank you ifrog,

    I follow the tutorial and there they aply a rigid body, can I apply the script without disable the rigid body?

    Thank you in advance
     
  4. hsparra

    hsparra

    Joined:
    Jul 12, 2005
    Posts:
    750
    You should be able to. If you are using the rigid body to move the car by adding forces, rigidbody.AddRelativeForce() and rigidbody.AddRelativeTorque(), then you can query the rigid body for its velocity. If you do that the check the square magnitude of teh velocity to see if it is less than a given value.
     
  5. joacoerazo_legacy

    joacoerazo_legacy

    Joined:
    Apr 5, 2006
    Posts:
    214
    Many thanks!!!

    I will try it